### Docker Installation for Sheet API Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Instructions for installing and running the Sheet API using Docker. This includes pulling the Docker image and running a container with specified environment variables and volume mounts for credentials. ```bash docker pull utsmannn/sheet-api:latest docker run -d \ -p 8910:8910 \ -e SHEET_ID="your_google_sheet_id" \ -e API_SECRET_KEY="your-secret-key" \ -e CREDENTIAL_PATH="/app/credentials/service-account.json" \ -v /path/on/your/machine/service-account.json:/app/credentials/service-account.json \ --name sheet-api \ utsmannn/sheet-api:latest ``` -------------------------------- ### Get Sheet Names (API Request) Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Example cURL commands to retrieve the names of all sheets (tabs) within a Google Spreadsheet. Two variations are shown: one for the default sheet ID and another for a custom sheet ID. Requires an API key for authentication. ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets" curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/{sheetId}" ``` -------------------------------- ### Get Sheet Data with Hierarchical Grouping (API Request) Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Example cURL command to retrieve data from a Google Sheet using the Sheet API. This endpoint supports automatic hierarchical grouping, merging scattered data into parent objects. Requires an API key for authentication. ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/{sheetId}/{sheetName}" ``` -------------------------------- ### Get Sheet Schema (GET) Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Retrieves the detected schema from sheet headers, including auto-detected data types. Supports fetching schema for a default sheet ID or a custom sheet ID. Requires an API key. ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets/{sheetName}/schema" ``` ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/{sheetId}/{sheetName}/schema" ``` -------------------------------- ### Docker Deployment - Production Container Setup (bash) Source: https://context7.com/utsmannn/sheet-api/llms.txt This section provides bash commands for deploying the Sheet API using Docker in a production environment. It includes pulling the latest image, setting up a credentials directory, running the container with environment variables and volume mounts, and performing health checks. ```bash # Pull latest image from Docker Hub docker pull utsmannn/sheet-api:latest # Create credentials directory mkdir -p ./credentials cp service-account.json ./credentials/ # Run with environment variables docker run -d \ -p 8910:8910 \ -e SHEET_ID="1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms" \ -e API_SECRET_KEY="production-secret-key-2024" \ -e CREDENTIAL_PATH="/app/credentials/service-account.json" \ -e JAVA_OPTS="-Xmx512m -Xms256m" \ -v $(pwd)/credentials:/app/credentials:ro \ --name sheet-api \ --restart unless-stopped \ utsmannn/sheet-api:latest # Check container health docker ps docker logs sheet-api # Test health endpoint curl http://localhost:8910/ # Response: 200 OK with landing page HTML # Stop and remove container docker stop sheet-api docker rm sheet-api ``` -------------------------------- ### GET /api/sheets/{sheetName}/schema Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Returns the detected schema from sheet headers (A1-Z1) with auto-detected data types for a specified sheet name. ```APIDOC ## GET /api/sheets/{sheetName}/schema ### Description Returns the detected schema from sheet headers (A1-Z1) with auto-detected data types. ### Method GET ### Endpoint `/api/sheets/{sheetName}/schema` ### Parameters #### Path Parameters - **sheetName** (string) - Required - The name of the sheet. ### Request Example ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets/{sheetName}/schema" ``` ### Response #### Success Response (200) - **schema** (object) - An object representing the schema with detected data types. #### Response Example ```json { "schema": { "columnA": "string", "columnB": "number" } } ``` ``` -------------------------------- ### Docker Compose Management Commands (bash) Source: https://context7.com/utsmannn/sheet-api/llms.txt This section provides essential bash commands for managing Docker Compose services. It covers creating a `.env` file for environment variables, starting services in detached mode, viewing logs, checking service status, restarting services, and tearing down the entire stack. ```bash # Create .env file for docker-compose cat > .env << EOF SHEET_ID=1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms API_SECRET_KEY=production-secret-key-2024 EOF # Start services with docker-compose docker-compose up -d # View logs docker-compose logs -f sheet-api # Check service status docker-compose ps # Restart service docker-compose restart sheet-api # Stop and remove all services docker-compose down ``` -------------------------------- ### GET /api/sheets Source: https://context7.com/utsmannn/sheet-api/llms.txt Fetches a list of all available sheet names within the spreadsheet. ```APIDOC ## GET /api/sheets ### Description Fetches a list of all available sheet names within the spreadsheet. ### Method GET ### Endpoint /api/sheets ### Parameters #### Query Parameters - **X-API-Key** (string) - Required - The API key for authentication. ### Request Example ```http GET /api/sheets HTTP/1.1 Host: your-api-host.com X-API-Key: YOUR_API_KEY Content-Type: application/json ``` ### Response #### Success Response (200) - **sheets** (array) - A list of sheet names. Each item is a dictionary potentially containing sheet details. #### Response Example ```json { "sheets": [ {"name": "Sheet1"}, {"name": "Sheet2"} ] } ``` ``` -------------------------------- ### Fetch Paginated Sheet Data with cURL Source: https://context7.com/utsmannn/sheet-api/llms.txt Examples of fetching paginated data from a sheet using cURL. It demonstrates accessing general sheet data and specific sheets by ID. Requires an API key for authentication. ```bash # Get paginated flat data curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets/Products?per_page=20&offset=1" # Access sheet from different spreadsheet curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/1ABC123XYZ456/Inventory" ``` -------------------------------- ### Generate and Use Time-Based API Keys (Bash, Node.js, Python) Source: https://context7.com/utsmannn/sheet-api/llms.txt Demonstrates how to generate secure, time-based API keys for authenticating requests to the Sheet API. It includes examples for Bash, Node.js, and Python, along with how to use the generated key with `X-API-Key` or `Authorization` headers. ```bash # Generate API key using bash (Linux/Mac) API_SECRET_KEY="my-secret-key" timestamp=$(date +%s)000 api_key=$(printf "${API_SECRET_KEY}:${timestamp}" | base64) echo "Generated API Key: ${api_key}" # Output example: bXktc2VjcmV0LWtleToxNzMwNzU4ODAwMDAw # Use the API key with X-API-Key header curl -H "X-API-Key: ${api_key}" \ http://localhost:8910/api/sheets # Or use Authorization Bearer header curl -H "Authorization: Bearer ${api_key}" \ http://localhost:8910/api/sheets ``` ```javascript // Generate API key using Node.js const secretKey = process.env.API_SECRET_KEY || 'my-secret-key'; const timestamp = Date.now(); // Already in milliseconds const apiKey = Buffer.from(`${secretKey}:${timestamp}`).toString('base64'); console.log('Generated API Key:', apiKey); // Use in fetch requests const response = await fetch('http://localhost:8910/api/sheets/MySheet', { headers: { 'X-API-Key': apiKey, 'Content-Type': 'application/json' } }); const data = await response.json(); console.log(data); ``` ```python # Generate API key using Python import base64 import time import os secret_key = os.getenv('API_SECRET_KEY', 'my-secret-key') timestamp = int(time.time() * 1000) # Convert to milliseconds api_key = base64.b64encode(f"{secret_key}:{timestamp}".encode()).decode() print(f"Generated API Key: {api_key}") # Use in requests import requests headers = {'X-API-Key': api_key} response = requests.get('http://localhost:8910/api/sheets/MySheet', headers=headers) print(response.json()) ``` -------------------------------- ### Docker Compose Commands for Updating Sheet API Source: https://context7.com/utsmannn/sheet-api/llms.txt These commands are used to update the Sheet API to its latest Docker image and restart the services. It requires Docker and Docker Compose to be installed and configured. ```bash docker-compose pull docker-compose up -d ``` -------------------------------- ### GET /api/sheetId/{sheetId}/{sheetName}/schema Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Returns the detected schema from sheet headers (A1-Z1) with auto-detected data types for a specific sheet ID and name. ```APIDOC ## GET /api/sheetId/{sheetId}/{sheetName}/schema ### Description Returns the detected schema from sheet headers (A1-Z1) with auto-detected data types for a custom sheet ID and name. ### Method GET ### Endpoint `/api/sheetId/{sheetId}/{sheetName}/schema` ### Parameters #### Path Parameters - **sheetId** (string) - Required - The ID of the sheet. - **sheetName** (string) - Required - The name of the sheet. ### Request Example ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/{sheetId}/{sheetName}/schema" ``` ### Response #### Success Response (200) - **schema** (object) - An object representing the schema with detected data types. #### Response Example ```json { "schema": { "columnA": "string", "columnB": "number" } } ``` ``` -------------------------------- ### Retrieve Sheet Schema with cURL Source: https://context7.com/utsmannn/sheet-api/llms.txt Examples of retrieving the schema for a sheet using cURL. This allows for understanding the data structure and inferred data types. Requires an API key for authentication. ```bash # Get schema for default spreadsheet curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets/Products/schema" ``` -------------------------------- ### GET /api/sheets/{sheet_name} Source: https://context7.com/utsmannn/sheet-api/llms.txt Fetches data from a specific sheet, with options for pagination. Automatically detects the data format. ```APIDOC ## GET /api/sheets/{sheet_name} ### Description Fetches data from a specific sheet, with options for pagination. Automatically detects the data format. ### Method GET ### Endpoint /api/sheets/{sheet_name} ### Parameters #### Path Parameters - **sheet_name** (string) - Required - The name of the sheet to retrieve data from. #### Query Parameters - **per_page** (integer) - Optional - The number of records to return per page. Defaults to 10. - **offset** (integer) - Optional - The offset for pagination. Defaults to 1. - **X-API-Key** (string) - Required - The API key for authentication. ### Request Example ```http GET /api/sheets/Sheet1?per_page=20&offset=2 HTTP/1.1 Host: your-api-host.com X-API-Key: YOUR_API_KEY Content-Type: application/json ``` ### Response #### Success Response (200) - **data** (object/array) - The data retrieved from the sheet. The structure depends on the sheet's format. - **total_count** (integer) - The total number of records available in the sheet (from X-Total-Count header). #### Response Example ```json { "data": [ {"column1": "value1", "column2": "value2"}, {"column1": "value3", "column2": "value4"} ], "total_count": 50 } ``` ``` -------------------------------- ### Get Sheet Names Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Retrieves a list of all sheet (tab) names within a Google Spreadsheet. Can be used with the default sheet ID or a custom sheet ID. ```APIDOC ## GET /api/sheets ### Description Retrieves the names of all sheets (tabs) in the default Google Spreadsheet. ### Method GET ### Endpoint /api/sheets ### Parameters None ### Request Example ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets" ``` ### Response #### Success Response (200) - **(array of strings)** - A list of sheet names. #### Response Example ```json { "example": "response body" } ``` ## GET /api/sheetId/{sheetId} ### Description Retrieves the names of all sheets (tabs) in a Google Spreadsheet specified by the `sheetId`. ### Method GET ### Endpoint /api/sheetId/{sheetId} ### Parameters #### Path Parameters - **sheetId** (string) - Required - The ID of the Google Sheet. ### Request Example ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/{sheetId}" ``` ### Response #### Success Response (200) - **(array of strings)** - A list of sheet names. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Python Sheet API Complete Workflow Example Source: https://context7.com/utsmannn/sheet-api/llms.txt This Python script demonstrates a full integration workflow with the Sheet API. It initializes a client, lists sheet names, fetches schema and data, adds a new record, updates an existing record, and performs operations on hierarchical data. It includes error handling for HTTP errors and general exceptions. ```python import requests import json # Assuming SheetAPIClient is defined elsewhere or imported # from sheet_api_client import SheetAPIClient class SheetAPIClient: def __init__(self, base_url, api_secret): self.base_url = base_url self.api_secret = api_secret # In a real scenario, you would set up authentication headers here print(f"Initializing SheetAPIClient with base_url: {base_url}") def get_sheet_names(self): # Mock response for demonstration print("Mock: Fetching sheet names...") return [{'sheet': 'Products'}, {'sheet': 'Courses'}] def get_schema(self, sheet_name): # Mock response for demonstration print(f"Mock: Fetching schema for {sheet_name}...") if sheet_name == 'Products': return {'schema': {'type': 'object', 'properties': {'id': {'type': 'string'}, 'name': {'type': 'string'}, 'price': {'type': 'string'}, 'in_stock': {'type': 'string'}, 'description': {'type': 'string'}}}} return {'schema': {'type': 'object'}} def get_data(self, sheet_name, per_page=10, offset=0): # Mock response for demonstration print(f"Mock: Fetching data for {sheet_name} (offset: {offset}, per_page: {per_page})...") if sheet_name == 'Products': return { 'total_count': 10, 'data': [ {'id': '1', 'name': 'Basic Widget', 'price': '99.99', 'in_stock': 'true', 'description': 'A standard widget'}, {'id': '2', 'name': 'Advanced Gadget', 'price': '199.99', 'in_stock': 'false', 'description': 'A sophisticated gadget'} ] } elif sheet_name == 'Courses': return { 'total_count': 1, 'data': { 'title': 'Introduction to APIs', 'Curriculums': [ {'name': 'Basics', 'content': []}, {'name': 'Advanced Topics', 'content': []} ] } } return {'total_count': 0, 'data': []} def add_record(self, sheet_name, record, identifiers=None): # Mock response for demonstration print(f"Mock: Adding record to {sheet_name} with data: {record} and identifiers: {identifiers}...") return {'updatedRange': f'{sheet_name}!A1'} def update_field(self, sheet_name, field_updates, identifiers): # Mock response for demonstration print(f"Mock: Updating {sheet_name} with {field_updates} for identifiers: {identifiers}...") return {'updatedRange': f'{sheet_name}!B2'} def main(): # Initialize client client = SheetAPIClient( base_url='http://localhost:8910', api_secret='my-secret-key' ) print("=== Sheet API Integration Example ===\n") # 1. List all sheets print("1. Fetching all sheet names...") sheets = client.get_sheet_names() for sheet in sheets: print(f" - {sheet['sheet']}") # 2. Get schema print("\n2. Fetching Products schema...") schema = client.get_schema('Products') print(f" Schema type: {schema['schema']['type']}") # 3. Fetch existing data print("\n3. Fetching Products data...") result = client.get_data('Products', per_page=5, offset=1) print(f" Total records: {result['total_count']}") print(f" Fetched: {len(result['data'])} records") # 4. Add new product print("\n4. Adding new product...") new_product = { 'id': '999', 'name': 'Ultimate Widget', 'price': '499.99', 'in_stock': 'true', 'description': 'The best widget ever made' } add_result = client.add_record('Products', new_product) print(f" ✓ Added at: {add_result['updatedRange']}") # 5. Update existing product print("\n5. Updating product price...") update_result = client.update_field( 'Products', {'price': '449.99'}, identifiers={'id': '999'} ) print(f" ✓ Updated at: {update_result['updatedRange']}") # 6. Work with hierarchical data print("\n6. Working with hierarchical course data...") courses_result = client.get_data('Courses') courses_data = courses_result['data'] if isinstance(courses_data, dict): print(f" Course: {courses_data.get('title')}") print(f" Curriculums: {len(courses_data.get('Curriculums', []))}") # Add nested content new_content = { 'content_name': 'Advanced Debugging', 'content_url': 'https://videos.com/debugging', 'duration': '35' } add_nested_result = client.add_record( 'Courses', new_content, identifiers={'Curriculum': 'Advanced Topics'} ) print(f" ✓ Added nested content at: {add_nested_result['updatedRange']}") print("\n=== Integration complete! ===") if __name__ == '__main__': try: main() except requests.exceptions.HTTPError as e: print(f"HTTP Error: {e.response.status_code}") print(json.dumps(e.response.json(), indent=2)) except Exception as e: print(f"Error: {str(e)}") ``` -------------------------------- ### Add New Row to Sheet (API Request) Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Example cURL commands for appending data to a Google Sheet via the Sheet API. Demonstrates adding a root-level item and a nested item using query parameters for targeting specific groups. Requires an API key and JSON content. ```bash curl -X POST \ -H "X-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"title": "New Course", "author": "admin"}' \ "http://localhost:8910/api/sheetId/{sheetId}/{sheetName}" curl -X POST \ -H "X-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"content_name": "New Content", "content_description": "..."}' \ "http://localhost:8910/api/sheetId/{sheetId}/{sheetName}?curriculums=Pengenalan%20Python" ``` -------------------------------- ### GET /api/sheets/{sheet_name}/schema Source: https://context7.com/utsmannn/sheet-api/llms.txt Fetches the schema of a specific sheet, including inferred data types for each field. ```APIDOC ## GET /api/sheets/{sheet_name}/schema ### Description Fetches the schema of a specific sheet, including inferred data types for each field. ### Method GET ### Endpoint /api/sheets/{sheet_name}/schema ### Parameters #### Path Parameters - **sheet_name** (string) - Required - The name of the sheet to retrieve the schema for. #### Query Parameters - **X-API-Key** (string) - Required - The API key for authentication. ### Request Example ```http GET /api/sheets/Sheet1/schema HTTP/1.1 Host: your-api-host.com X-API-Key: YOUR_API_KEY Content-Type: application/json ``` ### Response #### Success Response (200) - **schema** (object) - An object describing the schema of the sheet. Keys are field names, and values describe their types and properties. #### Response Example ```json { "schema": { "column1": {"type": "string"}, "column2": {"type": "integer"} } } ``` ``` -------------------------------- ### Get Sheet Data Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Retrieves data from a specified sheet. It automatically detects and merges hierarchical data, returning a nested JSON structure. Supports access to the default sheet or a custom sheet ID. ```APIDOC ## GET /api/sheetId/{sheetId}/{sheetName} ### Description Retrieves data from the sheet with automatic hierarchical grouping. If it detects data in the same group scattered across the sheet, it intelligently merges them into a single parent object. ### Method GET ### Endpoint /api/sheetId/{sheetId}/{sheetName} ### Parameters #### Path Parameters - **sheetId** (string) - Required - The ID of the Google Sheet. - **sheetName** (string) - Required - The name of the sheet (tab) within the spreadsheet. #### Query Parameters None ### Request Example ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/{sheetId}/{sheetName}" ``` ### Response #### Success Response (200) - **(object)** - The sheet data, potentially nested based on hierarchical grouping. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### GET /api/sheetId/{sheet_id}/{sheet_name} Source: https://context7.com/utsmannn/sheet-api/llms.txt Fetches data from a specific sheet using a sheet ID, with options for pagination. ```APIDOC ## GET /api/sheetId/{sheet_id}/{sheet_name} ### Description Fetches data from a specific sheet using a sheet ID, with options for pagination. ### Method GET ### Endpoint /api/sheetId/{sheet_id}/{sheet_name} ### Parameters #### Path Parameters - **sheet_id** (string) - Required - The ID of the spreadsheet. - **sheet_name** (string) - Required - The name of the sheet to retrieve data from. #### Query Parameters - **per_page** (integer) - Optional - The number of records to return per page. Defaults to 10. - **offset** (integer) - Optional - The offset for pagination. Defaults to 1. - **X-API-Key** (string) - Required - The API key for authentication. ### Request Example ```http GET /api/sheetId/YOUR_SHEET_ID/Sheet1?per_page=20&offset=2 HTTP/1.1 Host: your-api-host.com X-API-Key: YOUR_API_KEY Content-Type: application/json ``` ### Response #### Success Response (200) - **data** (object/array) - The data retrieved from the sheet. - **total_count** (integer) - The total number of records available in the sheet (from X-Total-Count header). #### Response Example ```json { "data": [ {"column1": "value1", "column2": "value2"} ], "total_count": 50 } ``` ``` -------------------------------- ### GET /api/sheets - List Available Sheets Source: https://context7.com/utsmannn/sheet-api/llms.txt Retrieve a list of all sheet tabs (pages) within a Google Spreadsheet. Supports pagination and filtering by specific fields. ```APIDOC ## GET /api/sheets - List Available Sheets ### Description Retrieve list of all sheet tabs (pages) in the spreadsheet with pagination support. You can also specify fields to retrieve from the first row of each sheet. ### Method GET ### Endpoint `/api/sheets` ### Parameters #### Query Parameters - **per_page** (integer) - Optional - The number of results to return per page. - **offset** (integer) - Optional - The number of results to skip. Used for pagination. - **fields** (string) - Optional - A comma-separated list of fields to retrieve from the first row of each sheet (e.g., `title,author,status`). #### Path Parameters None #### Request Body None ### Request Example ```bash # Get all sheet names from default spreadsheet curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets" # Get sheet names with pagination curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets?per_page=5&offset=1" # Get only specific fields from first row curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets?fields=title,author,status" ``` ### Response #### Success Response (200) - **sheet** (string) - The name of the sheet. - **data** (object) - An object containing data from the first row of the sheet, if `fields` parameter is used. Response headers include `X-Total-Count` indicating the total number of sheets. #### Response Example ```json [ {"sheet": "Courses", "data": {"title": "Python Programming"}}, {"sheet": "Students", "data": {"name": "John Doe"}}, {"sheet": "Instructors", "data": {"instructor": "Jane Smith"}} ] ``` #### Error Response - **401 Unauthorized**: If the API key is invalid or missing. - **500 Internal Server Error**: For server-side issues. ``` -------------------------------- ### JavaScript Client for Sheet API Source: https://context7.com/utsmannn/sheet-api/llms.txt Provides a JavaScript function `updateSheetField` to programmatically interact with the Sheet API for updating data. Includes examples for single field updates, nested field updates, and batch updates. ```javascript // Update multiple records with intelligent targeting async function updateSheetField(sheetName, fieldUpdate, identifiers, apiKey) { const url = new URL(`http://localhost:8910/api/sheets/${sheetName}`); // Add identifiers as query parameters if (identifiers) { Object.entries(identifiers).forEach(([key, value]) => { url.searchParams.append(key, value); }); } const response = await fetch(url, { method: 'PATCH', headers: { 'X-API-Key': apiKey, 'Content-Type': 'application/json' }, body: JSON.stringify(fieldUpdate) }); if (response.ok) { const result = await response.json(); console.log(`✓ Updated: ${result.updatedRange}`); return result; } else { const error = await response.json(); console.error(`✗ Update failed:`, error); throw new Error(error.error); } } // Example: Update product price updateSheetField( 'Products', { price: '999.99' }, { id: '101' }, 'YOUR_API_KEY' ); // Example: Update nested curriculum content updateSheetField( 'Courses', { content_url: 'https://new-platform.com/video/updated' }, { Curriculum: 'Introduction to Python', content_name: 'Variables and Data Types' }, 'YOUR_API_KEY' ); // Example: Batch update multiple fields (sequential) async function batchUpdateFields() { const updates = [ { field: { in_stock: 'false' }, id: { id: '101' } }, { field: { in_stock: 'true' }, id: { id: '102' } }, { field: { price: '129.99' }, id: { id: '103' } } ]; for (const update of updates) { await updateSheetField('Products', update.field, update.id, 'YOUR_API_KEY'); } } ``` -------------------------------- ### Update with URL-Encoded Special Characters (curl) Source: https://context7.com/utsmannn/sheet-api/llms.txt This example illustrates how to handle special characters in URL parameters by URL-encoding them. It uses the PATCH method to update a 'status' field and demonstrates the encoding of characters like '&' in the 'task_name' query parameter. ```bash curl -X PATCH \ -H "X-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"status": "completed"}' \ "http://localhost:8910/api/sheets/Tasks?project=Q4%20Launch&task_name=Design%20%26%20Development" ``` -------------------------------- ### Update Nested Field using Multiple Identifiers (curl) Source: https://context7.com/utsmannn/sheet-api/llms.txt This example shows how to update a field by providing multiple identifiers for more precise targeting. It uses the PATCH method and includes the API key and content type in the headers. The request body contains the field to update, and the URL includes multiple query parameters for identification. ```bash curl -X PATCH \ -H "X-API-Key: YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"duration": "45"}' \ "http://localhost:8910/api/sheets/Courses?Curriculum=Functions%20and%20Modules&content_name=Defining%20Functions" ``` -------------------------------- ### Build and Run Project Tasks Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Lists essential Gradle tasks for building, testing, and running the project, including creating an executable JAR, building a Docker image, and deploying services. ```bash ./gradlew test ./gradlew build buildFatJar buildImage publishImageToLocalRegistry run runDocker ``` -------------------------------- ### GET /api/sheetId/:spreadsheetId - Get Sheets by Spreadsheet ID Source: https://context7.com/utsmannn/sheet-api/llms.txt Retrieve sheet names from a specific Google Spreadsheet identified by its unique ID. ```APIDOC ## GET /api/sheetId/:spreadsheetId - Get Sheets by Spreadsheet ID ### Description Retrieve a list of all sheet tabs (pages) from a specific Google Spreadsheet using its unique ID. This endpoint allows access to any Google Sheet without changing environment variables. ### Method GET ### Endpoint `/api/sheetId/:spreadsheetId` ### Parameters #### Path Parameters - **spreadsheetId** (string) - Required - The unique ID of the Google Spreadsheet. #### Query Parameters None #### Request Body None ### Request Example ```bash # Get sheet names from specific spreadsheet by ID curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms" ``` ### Response #### Success Response (200) - **sheet** (string) - The name of the sheet. - **data** (object) - An object containing data from the first row of the sheet, if `fields` parameter is used (Note: `fields` parameter not explicitly mentioned for this endpoint, but implied from general sheet access). #### Response Example ```json [ {"sheet": "Sheet1"}, {"sheet": "Data"}, {"sheet": "Summary"} ] ``` #### Error Response - **401 Unauthorized**: If the API key is invalid or missing. - **404 Not Found**: If the spreadsheet ID is invalid or inaccessible. - **500 Internal Server Error**: For server-side issues. ``` -------------------------------- ### Docker Compose Configuration for Sheet API Source: https://github.com/utsmannn/sheet-api/blob/main/README.md A Docker Compose configuration file (`docker-compose.yml`) for setting up and running the Sheet API. It defines the service, image, ports, environment variables, and volume mounts for credentials, and includes instructions for creating a `.env` file and a credentials directory. ```yaml version: '3.8' services: sheet-api: image: utsmannn/sheet-api:latest container_name: sheet-api-kotlin ports: - "8910:8910" environment: - SHEET_ID=${SHEET_ID} - API_SECRET_KEY=${API_SECRET_KEY} - CREDENTIAL_PATH=/app/credentials/service-account.json volumes: - ./credentials:/app/credentials:ro restart: unless-stopped ``` -------------------------------- ### Rebuild Landing Page Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Command to rebuild and deploy the React TypeScript landing page after making any necessary changes to its code or features. ```bash # Build and deploy the landing page ./build-frontend.sh ``` -------------------------------- ### GET /api/sheets/:sheetName - Get Sheet Data Source: https://context7.com/utsmannn/sheet-api/llms.txt Retrieve data from a specific sheet. The API automatically detects and formats the data as either flat JSON (for simple tables) or hierarchical JSON (for grouped data with merged cells). ```APIDOC ## GET /api/sheets/:sheetName - Get Sheet Data ### Description Automatically detects flat or grouped data structure and returns appropriate JSON format for the specified sheet. Supports pagination for large datasets. ### Method GET ### Endpoint `/api/sheets/:sheetName` ### Parameters #### Path Parameters - **sheetName** (string) - Required - The name of the sheet to retrieve data from. #### Query Parameters - **per_page** (integer) - Optional - The number of results to return per page. - **offset** (integer) - Optional - The number of results to skip. Used for pagination. #### Request Body None ### Request Example ```bash # Get data with automatic format detection from 'Courses' sheet curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets/Courses" ``` ### Response #### Success Response (200) The structure of the response depends on the sheet's data organization: **Example flat data response (simple table):** ```json [ {"id": "1", "name": "Introduction to Python", "price": "99.99", "active": "true"}, {"id": "2", "name": "Advanced JavaScript", "price": "149.99", "active": "true"}, {"id": "3", "name": "Web Development", "price": "199.99", "active": "false"} ] ``` Headers include `X-Total-Count` indicating the total number of rows. **Example hierarchical response (grouped data with merged cells):** ```json { // Hierarchical structure based on merged cells and grouping } ``` #### Error Response - **401 Unauthorized**: If the API key is invalid or missing. - **404 Not Found**: If the specified sheet name does not exist. - **500 Internal Server Error**: For server-side issues. ``` -------------------------------- ### Using API Keys in Requests Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Demonstrates two common methods for including the generated API key in requests to protected endpoints: using the 'X-API-Key' header or the 'Authorization: Bearer' header. ```bash curl -H "X-API-Key: YOUR_API_KEY" http://localhost:8910/api/sheets/MySheet ``` ```bash curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost:8910/api/sheets/MySheet ``` -------------------------------- ### Generate API Keys (Command Line) Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Generates an API key using a secret key and the current timestamp in milliseconds. This method is suitable for Linux/Mac environments. ```bash # Generate current timestamp in milliseconds timestamp=$(date +%s)000 printf "my-secret-key:$timestamp" | base64 ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Sets essential environment variables for the Sheet API, including the default sheet ID, credential path for authentication, and the secret key for API key generation. ```bash export SHEET_ID="your_default_google_sheet_id" # Optional: fallback when no sheetId in path export CREDENTIAL_PATH="/path/to/service-account.json" export API_SECRET_KEY="your-secret-key-for-api-key-generation" ``` -------------------------------- ### API Authentication Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Details on how to authenticate API requests using API keys, including generation and usage. ```APIDOC ## API Authentication All API endpoints are protected with API key authentication, except for public endpoints: - Root (`/`) - Health checks (`/health*`) - Documentation (`/swagger*`, `/openapi*`, `/docs*`) ### Generating API Keys API keys use the format: `base64("{API_SECRET_KEY}:{13_digit_timestamp}")` #### Option 1: Command Line (Linux/Mac) ```bash # Generate current timestamp in milliseconds timestamp=$(date +%s)000 printf "my-secret-key:$timestamp" | base64 ``` #### Option 2: Node.js ```javascript const secretKey = process.env.API_SECRET_KEY || 'my-secret-key'; const timestamp = Date.now(); // Already in milliseconds const apiKey = Buffer.from(`${secretKey}:${timestamp}`).toString('base64'); console.log(apiKey); ``` ### Using API Keys Include the API key in your requests using either header format: **Option 1: X-API-Key Header** ```bash curl -H "X-API-Key: YOUR_API_KEY" http://localhost:8910/api/sheets/MySheet ``` **Option 2: Authorization Bearer Header** ```bash curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost:8910/api/sheets/MySheet ``` ``` -------------------------------- ### Docker Compose - Production Deployment Configuration (yaml) Source: https://context7.com/utsmannn/sheet-api/llms.txt This `docker-compose.yml` file defines the production deployment configuration for the Sheet API. It specifies the image, ports, environment variables, volume mounts, network settings, and a health check for the service, ensuring a robust and manageable deployment. ```yaml version: '3.8' services: sheet-api: image: utsmannn/sheet-api:latest container_name: sheet-api-kotlin ports: - "8910:8910" environment: - SHEET_ID=${SHEET_ID} - API_SECRET_KEY=${API_SECRET_KEY} - CREDENTIAL_PATH=/app/credentials/service-account.json - JAVA_OPTS=-Xmx512m -Xms256m volumes: - ./credentials:/app/credentials:ro networks: - sheet-api-network restart: unless-stopped healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8910/"] interval: 30s timeout: 10s retries: 3 start_period: 40s networks: sheet-api-network: driver: bridge ``` -------------------------------- ### Get Sheet Schema Source: https://context7.com/utsmannn/sheet-api/llms.txt Retrieve the schema for a given sheet, including auto-detected data types and structure, useful for data validation. ```APIDOC ## GET /api/sheets/{sheet_name}/schema ### Description Retrieves the schema of a specified sheet, including inferred data types and required fields. This is useful for validating data before submission or understanding data structure. ### Method GET ### Endpoint `/api/sheets/{sheet_name}/schema` ### Parameters #### Path Parameters - **sheet_name** (string) - Required - The name of the sheet for which to retrieve the schema. ### Request Example ```bash # Get schema for default spreadsheet curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets/Products/schema" ``` ### Response #### Success Response (200) - **sheetName** (string) - The name of the sheet. - **schema** (object) - An object describing the schema of the sheet data. This object follows a structure similar to JSON Schema, detailing types, properties, and required fields for both flat and hierarchical data. ``` -------------------------------- ### GET /api/sheetId/{sheetId}/{sheetName}/schema Source: https://context7.com/utsmannn/sheet-api/llms.txt Retrieves the schema for a specific spreadsheet. This is useful for understanding the structure and expected data types. ```APIDOC ## GET /api/sheetId/{sheetId}/{sheetName}/schema ### Description Retrieves the schema for a specific spreadsheet. This is useful for understanding the structure and expected data types. ### Method GET ### Endpoint `/api/sheetId/{sheetId}/{sheetName}/schema` ### Parameters #### Path Parameters - **sheetId** (string) - Required - The ID of the spreadsheet. - **sheetName** (string) - Required - The name of the sheet within the spreadsheet. #### Query Parameters None #### Request Body None ### Request Example ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/1ABC123XYZ456/Users/schema" ``` ### Response #### Success Response (200) - **schema** (object) - An object describing the schema of the sheet. #### Response Example ```json { "schema": { "type": "array", "items": { "type": "object", "properties": { "id": {"type": "string"}, "name": {"type": "string"}, "price": {"type": "number"}, "active": {"type": "boolean"} } } } } ``` ``` -------------------------------- ### Integrate ESLint Plugins for React and React DOM Linting Source: https://github.com/utsmannn/sheet-api/blob/main/landingpage/README.md This JavaScript code shows how to integrate 'eslint-plugin-react-x' and 'eslint-plugin-react-dom' into your ESLint configuration. It enables recommended lint rules for both React and React DOM, enhancing code quality for React projects. This configuration also requires project TypeScript configuration files for parsing. ```javascript // eslint.config.js import reactX from 'eslint-plugin-react-x' import reactDom from 'eslint-plugin-react-dom' export default defineConfig([ globalIgnores(['dist']), { files: ['**/*.{ts,tsx}'], extends: [ // Other configs... // Enable lint rules for React reactX.configs['recommended-typescript'], // Enable lint rules for React DOM reactDom.configs.recommended, ], languageOptions: { parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, // other options... }, }, ]) ``` -------------------------------- ### Get Paginated Flat Data Source: https://context7.com/utsmannn/sheet-api/llms.txt Retrieve paginated data from a sheet. The API automatically detects if the data is flat (an array of objects) or hierarchical (a nested object). ```APIDOC ## GET /api/sheets/{sheet_name} ### Description Retrieves paginated data from a specified sheet. The response format (flat or hierarchical) is determined by the sheet's structure. ### Method GET ### Endpoint `/api/sheets/{sheet_name}` ### Parameters #### Query Parameters - **per_page** (integer) - Optional - The number of items to return per page. - **offset** (integer) - Optional - The number of items to skip before starting to collect the result set. ### Request Example ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheets/Products?per_page=20&offset=1" ``` ### Response #### Success Response (200) - **data** (array or object) - The sheet data, either as a flat array of objects or a hierarchical object. - **X-Total-Count** (integer) - The total number of items available for the sheet. ``` -------------------------------- ### Get Schema from Spreadsheet Source: https://context7.com/utsmannn/sheet-api/llms.txt Retrieves the schema for a specified spreadsheet. This is useful for understanding the structure and data types of a sheet before fetching or manipulating data. It requires an API key and the sheet ID. ```bash curl -H "X-API-Key: YOUR_API_KEY" \ "http://localhost:8910/api/sheetId/1ABC123XYZ456/Users/schema" ``` -------------------------------- ### Generate API Keys (Node.js) Source: https://github.com/utsmannn/sheet-api/blob/main/README.md Generates an API key using a secret key and the current timestamp in milliseconds. This method is suitable for Node.js environments. ```javascript const secretKey = process.env.API_SECRET_KEY || 'my-secret-key'; const timestamp = Date.now(); // Already in milliseconds const apiKey = Buffer.from(`${secretKey}:${timestamp}`).toString('base64'); console.log(apiKey); ```