### Get Server Version Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Fetches the current version of the Actual Server. Useful for compatibility checks. ```javascript const version = await budget.getServerVersion(); ``` -------------------------------- ### Run Directly with Node.js Source: https://github.com/jhonderson/actual-http-api/blob/main/README.md Install dependencies and start the service directly using Node.js. Create a .env file for local development environment variables. ```bash npm install npm start # or node server.js ``` -------------------------------- ### Get Budgets Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves a list of all available budgets on the server. Use this to manage multiple budget files. ```javascript const budgets = await budget.getBudgets(); ``` -------------------------------- ### Set Up Environment Variables and Start Service Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/README.md Configure necessary environment variables for the Actual server URL, password, and API key. Then, start the service and access the Swagger UI. ```bash # Set required environment variables export ACTUAL_SERVER_URL="http://actual-server:5006/" export ACTUAL_SERVER_PASSWORD="your-actual-password" export API_KEY="your-generated-api-key" # Start the service npm start # Access Swagger UI open http://localhost:5007/api-docs/ ``` -------------------------------- ### Get Accounts Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves all accounts linked to the budget. Use this to view current financial accounts. ```javascript const accounts = await budget.getAccounts(); ``` -------------------------------- ### Get Rules Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves all defined rules. Rules can automate transaction categorization or other actions. ```javascript const rules = await budget.getRules(); ``` -------------------------------- ### API Key Authorization Example Request Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Middleware.md Example cURL command to demonstrate how to send an API key in the request header for authentication. ```bash curl -H "x-api-key: secret-api-key" http://localhost:5007/v1/budgets/sync-id/accounts ``` -------------------------------- ### Get Transactions Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Fetches transactions for a given account. This is fundamental for reviewing financial activity. ```javascript const transactions = await budget.getTransactions("account-id"); ``` -------------------------------- ### Get Tags Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves all tags used in the budget. Tags are for custom organization of transactions or categories. ```javascript const tags = await budget.getTags(); ``` -------------------------------- ### Get File Content Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Reads the content of a file. Use this for accessing configuration files or data files. ```javascript const content = await getFileContent('/path/to/file.txt'); ``` -------------------------------- ### Get Payees Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves a list of payees. Useful for managing who you pay or receive money from. ```javascript const payees = await budget.getPayees(); ``` -------------------------------- ### API Key Authorization Header Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/CONFIGURATION.md Example of how to include the API key in the request header for authorization. This is enforced only in production mode. ```bash curl -H "x-api-key: your-api-key" http://localhost:5007/v1/budgets/sync-id/accounts ``` -------------------------------- ### Configuration Reference Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/README.md Details configuration and environment setup, including environment variables, secret management, configuration object schema, and Docker/deployment setup. ```APIDOC ## CONFIGURATION.md ### Description Documentation for configuration and environment setup, covering environment variables (required and optional), secret management (direct and file-based), configuration object schema, and Docker and deployment setup. ### Method N/A (This is a reference document) ### Endpoint N/A (This is a reference document) ### Parameters N/A (This is a reference document) ### Request Example N/A (This is a reference document) ### Response N/A (This is a reference document) ### Error Handling N/A (This is a reference document) ``` -------------------------------- ### Get Months Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves a list of months from the Budget module. Useful for iterating through monthly data. ```javascript const months = await budget.getMonths(); ``` -------------------------------- ### Create Schedule Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Sets up a new scheduled transaction or action. Use this for recurring bills or income. ```javascript const newSchedule = await budget.createSchedule({ // schedule details }); ``` -------------------------------- ### Get Schedules Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves scheduled transactions or actions. Useful for managing recurring financial events. ```javascript const schedules = await budget.getSchedules(); ``` -------------------------------- ### Example of Running an AQL Query Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Demonstrates how to construct and execute an AQL query using the `runQuery` method and the `q` object. ```javascript const results = await budget.runQuery( budget.q('transactions') .filter({ account: 'acct-id' }) .select(['date', 'amount']) ); ``` -------------------------------- ### Add New Endpoint Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/README.md Example of creating a new GET endpoint to handle custom budget method calls. Errors are caught and passed to the next middleware. ```javascript router.get('/budgets/:budgetSyncId/custom', async (req, res, next) => { try { const result = await res.locals.budget.customMethod(); res.json({ data: result }); } catch (err) { next(err); } }); ``` -------------------------------- ### Run Bank Sync Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Initiates synchronization with a linked bank account. Use this to import the latest transactions. ```javascript await budget.runBankSync(); ``` -------------------------------- ### Get Categories Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Fetches all categories associated with a budget. This is often a prerequisite for managing category-specific data. ```javascript const categories = await budget.getCategories(); ``` -------------------------------- ### Run Query Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Executes a custom query against the budget data. Use this for complex data retrieval and analysis. ```javascript const results = await budget.runQuery({ /* query parameters */ }); ``` -------------------------------- ### Create Account Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Adds a new account to the budget. This is for setting up new financial accounts like checking or savings. ```javascript const newAccount = await budget.createAccount("Account Name", "account-type"); ``` -------------------------------- ### GET /budgets/{budgetSyncId}/actualserverversion Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Fetches the version of the connected Actual Budget server for a specific budget. ```APIDOC ## GET /budgets/{budgetSyncId}/actualserverversion ### Description Returns the version of the connected Actual Budget server. ### Method GET ### Endpoint /budgets/{budgetSyncId}/actualserverversion ### Parameters #### Path Parameters - **budgetSyncId** (string) - Required - The unique identifier for the budget synchronization. ### Response #### Success Response (200) - **data** (string) - The version string of the Actual Budget server. ### Response Example ```json { "data": "26.6.0" } ``` ``` -------------------------------- ### Get Connected Actual Budget Server Version Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves the version of the Actual Budget server connected to a specific budget. ```json { "data": "26.6.0" } ``` -------------------------------- ### Create Tag Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Creates a new tag. Use this to add custom labels for better financial tracking. ```javascript const newTag = await budget.createTag("Tag Name"); ``` -------------------------------- ### Fetch Transactions with Pagination Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/README.md Get transactions for a specific account, filtering by date and using pagination. Specify the account ID, start date, page number, and limit per page. ```bash # Get transactions with pagination curl -H "x-api-key: key" \ "http://localhost:5007/v1/budgets/sync-id/accounts/acc-id/transactions?since_date=2023-08-01&page=1&limit=50" ``` -------------------------------- ### Get All Budget Rules Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Retrieves all budget rules. Use this to get a comprehensive list of all defined rules. ```javascript async getRules() ``` -------------------------------- ### Get Server Version Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Retrieves the current version of the Actual server. ```javascript async getServerVersion() ``` -------------------------------- ### Error Handler Example Usage Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Middleware.md Illustrates how a route handler passes errors to the errorHandler middleware using next(err). This example shows a scenario where a 'No budget exists' error leads to a 404 response. ```javascript // Route handler router.get('/budgets/:budgetSyncId/accounts', async (req, res, next) => { try { // If this throws 'No budget exists for sync-id: xxx' const accounts = await budget.getAccounts(); res.json({ data: accounts }); } catch (err) { next(err); // Passes to errorHandler } }); // Result: 404 with { error: 'No budget exists for sync-id: xxx' } ``` -------------------------------- ### Create Payee Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Adds a new payee to the system. Use this when setting up recurring payments or new recipients. ```javascript const newPayee = await budget.createPayee("Payee Name"); ``` -------------------------------- ### Create Rule Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Defines a new rule. Use this to automate repetitive tasks based on transaction patterns. ```javascript const newRule = await budget.createRule({ // rule definition }); ``` -------------------------------- ### GET /budgets/{budgetSyncId}/notes/budgetmonth/{budgetMonth} Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves notes for a specific budget month. ```APIDOC ## GET /budgets/{budgetSyncId}/notes/budgetmonth/{budgetMonth} ### Description Returns notes for a budget month. ### Method GET ### Endpoint /budgets/{budgetSyncId}/notes/budgetmonth/{budgetMonth} ### Parameters #### Path Parameters - **budgetMonth** (string) - Required - The budget month in YYYY-MM format. ### Response #### Success Response (200) - **data** (string) - The notes content for the budget month. ### Response Example ```json { "data": "string" } ``` ``` -------------------------------- ### Get All Budgets Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Retrieves a list of all budgets available on the server. ```javascript async getBudgets() ``` -------------------------------- ### Reopen Account Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Reactivates a previously closed account. Use this if a closed account needs to be used again. ```javascript await budget.reopenAccount("account-id"); ``` -------------------------------- ### Paginate Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Applies pagination logic to an array of items. Returns a subset of the items based on page and limit. ```javascript const paginatedItems = paginate(allItems, page, limit); ``` -------------------------------- ### BudgetMonth Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/TYPES.md Represents budget totals and category allocations for a specific month. Used to retrieve monthly budget summaries. ```json { "month": "2023-08", "incomeAvailable": 500000, "lastMonthOverspent": 0, "forNextMonth": 50000, "totalBudgeted": 400000, "toBudget": 50000, "fromLastMonth": 0, "totalIncome": 500000, "totalSpent": 400000, "totalBalance": 100000, "categoryGroups": [] } ``` -------------------------------- ### Get All Tags Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Retrieves a list of all tags. Use this to view all available tags for categorization. ```javascript async getTags() ``` -------------------------------- ### Configuration Directory Setup Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Utilities.md Sets up a directory structure for budget data and scans for existing budgets. It creates directories if they don't exist and reads metadata from existing budget configurations. ```javascript const { createDirIfDoesNotExist, getFileContent } = require('../utils/utils'); const path = require('path'); function setupBudgetDataDirectory(dataDir) { // Create directory structure createDirIfDoesNotExist(dataDir); // Scan for existing budgets const budgetDirs = listSubDirectories(dataDir); budgetDirs.forEach(budgetId => { const metadataPath = path.join(dataDir, budgetId, 'metadata.json'); try { const metadata = getFileContent(metadataPath); const parsed = JSON.parse(metadata); console.log(`Found budget: ${parsed.name} (ID: ${parsed.id})`); } catch (err) { console.error(`Error reading budget metadata: ${err.message}`); } }); } ``` -------------------------------- ### GET /budgets/{budgetSyncId}/months Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns a list of months for a given budget. ```APIDOC ## GET /budgets/{budgetSyncId}/months ### Description Returns list of months for the budget. ### Method GET ### Endpoint /budgets/{budgetSyncId}/months ### Response #### Success Response (200) - **data** (array) - A list of month strings in YYYY-MM format. ### Response Example ```json { "data": ["2023-07", "2023-08", "2023-09"] } ``` ``` -------------------------------- ### Export Data Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Exports budget data in a specified format. Useful for backups or analysis in other tools. ```javascript await budget.exportData("format", { /* export options */ }); ``` -------------------------------- ### GET /budgets/{budgetSyncId}/months/{month} Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns detailed budget information for a specific month. ```APIDOC ## GET /budgets/{budgetSyncId}/months/{month} ### Description Returns detailed budget information for a specific month. ### Method GET ### Endpoint /budgets/{budgetSyncId}/months/{month} ### Parameters #### Path Parameters - **month** (string) - Required - YYYY-MM format ### Response #### Success Response (200) - **data** (object) - Detailed budget information for the month. - **month** (string) - **incomeAvailable** (integer) - **lastMonthOverspent** (integer) - **forNextMonth** (integer) - **totalBudgeted** (integer) - **toBudget** (integer) - **fromLastMonth** (integer) - **totalIncome** (integer) - **totalSpent** (integer) - **totalBalance** (integer) - **categoryGroups** (array) ### Response Example ```json { "data": { "month": "2023-08", "incomeAvailable": integer, "lastMonthOverspent": integer, "forNextMonth": integer, "totalBudgeted": integer, "toBudget": integer, "fromLastMonth": integer, "totalIncome": integer, "totalSpent": integer, "totalBalance": integer, "categoryGroups": [] } } ``` ``` -------------------------------- ### GET /budgets/{budgetSyncId}/months/{month}/categorygroups Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns all category groups for a month. ```APIDOC ## GET /budgets/{budgetSyncId}/months/{month}/categorygroups ### Description Returns all category groups for a month. ### Method GET ### Endpoint /budgets/{budgetSyncId}/months/{month}/categorygroups ### Response #### Success Response (200) - **data** (array) - A list of category group objects. - **id** (string) - **name** (string) - **is_income** (boolean) - **hidden** (boolean) - **categories** (array) ### Response Example ```json { "data": [ { "id": "string", "name": "string", "is_income": boolean, "hidden": boolean, "categories": [] } ] } ``` ``` -------------------------------- ### Example of Using Query Builder Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Demonstrates constructing a complex AQL query using the query builder for filtering, grouping, and selecting data. ```javascript const result = await budget.runQuery( budget.q('transactions') .filter({ account: accountId }) .groupBy('category') .select(['category', { total: { $sum: '$amount' } }]) ); ``` -------------------------------- ### Get All Accounts Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Retrieves all accounts associated with the budget. Use this to list all available accounts. ```javascript async getAccounts() ``` ```javascript const accounts = await budget.getAccounts(); accounts.forEach(acc => console.log(acc.name)); ``` -------------------------------- ### GET /budgets/{budgetSyncId}/export Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Exports budget data as a ZIP file, including database and metadata. ```APIDOC ## GET /budgets/{budgetSyncId}/export ### Description Exports budget data as a ZIP file containing database and metadata. ### Method GET ### Endpoint /budgets/{budgetSyncId}/export ### Parameters #### Path Parameters - **budgetSyncId** (string) - Required - The unique identifier for the budget synchronization. ### Response #### Success Response (200) - File download with `Content-Type: application/zip` - Filename format: `YYYY-MM-DD-BudgetName.zip` ``` -------------------------------- ### Set Category Notes Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Adds or updates notes for a specific category. Use this to attach explanations or reminders to categories. ```javascript await budget.setCategoryNotes("category-id", "These are the notes for this category."); ``` -------------------------------- ### BudgetMonthCategory Object Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/TYPES.md Represents a category with budget allocation for a specific month. Use this for monthly budget tracking and updates. ```json { "id": "9fa2550c-c3ff-498b-8df6-e0fbe2a62e0e", "name": "Groceries", "is_income": false, "hidden": false, "group_id": "d4394761-0427-4ad4-bde7-9a83e118541a", "budgeted": 50000, "spent": 42350, "balance": 7650, "carryover": false } ``` -------------------------------- ### Server Startup Sequence Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ARCHITECTURE.md This snippet illustrates the typical startup sequence for the Express.js server. It covers configuration loading, middleware registration, API documentation setup, and connection listening. ```javascript // server.js - Application startup // 1. Load configuration const { config } = require('./src/config/config'); // - Reads environment variables // - Validates required secrets // - Throws if missing // 2. Create Express app const app = express(); app.use(express.json()); // 3. Register middleware app.use('/v1', v1Routes); // - v1Routes includes authorization // - v1Routes includes budget loader // - v1Routes includes all endpoints // - v1Routes includes error handler // 4. Setup Swagger UI app.use('/api-docs', swaggerUi.serve); app.get('/api-docs/swagger.json', (req, res) => res.json(openapiSpecification)); // 5. Listen for connections app.listen(config.port, () => { console.log("Actual HTTP Server Listening on PORT: ", config.port); }); // 6. Setup unhandled rejection handling process.on('unhandledRejection', ignoreUnhandledRejectionsCausedByActualApiLibrary); ``` -------------------------------- ### Current Local Date Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Gets the current date in the local timezone. Useful for timestamping or date-based operations. ```javascript const localDate = currentLocalDate(); ``` -------------------------------- ### GET /budgets/{budgetSyncId}/months/{month}/categorygroups/{categoryGroupId} Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns category group information for a month. ```APIDOC ## GET /budgets/{budgetSyncId}/months/{month}/categorygroups/{categoryGroupId} ### Description Returns category group information for a month. ### Method GET ### Endpoint /budgets/{budgetSyncId}/months/{month}/categorygroups/{categoryGroupId} ### Response #### Success Response (200) - **data** (object) - Category group information. - **id** (string) - **name** (string) - **is_income** (boolean) - **hidden** (boolean) - **categories** (array) ### Response Example ```json { "data": { "id": "string", "name": "string", "is_income": boolean, "hidden": boolean, "categories": [] } } ``` ``` -------------------------------- ### Run with Docker Compose Source: https://github.com/jhonderson/actual-http-api/blob/main/README.md Start the service using the docker-compose.yml configuration. Adjust environment variables in the compose file or override them with an .env file. ```bash docker-compose up -d ``` -------------------------------- ### Tag Object Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/TYPES.md Represents a user-defined label for organizing transactions. Includes an optional ID and a required name. ```json { "id": "tag-456", "name": "Important" } ``` -------------------------------- ### Get ID By Name Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves the ID of a budget by its name. Useful for programmatically accessing specific budgets. ```javascript const budgetId = await budget.getIDByName("Budget Name"); ``` -------------------------------- ### Create Category Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Creates a new category within the budget. Use this to add new spending or income categories. ```javascript const newCategory = await budget.createCategory("New Category Name"); ``` -------------------------------- ### GET /budgets Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns a list of available budgets on the server. This endpoint is experimental and requires access to the Actual data directory. ```APIDOC ## GET /budgets ### Description Returns list of available budgets on the server (experimental, requires reading Actual data directory). ### Method GET ### Endpoint /budgets ### Response #### Success Response (200) - **data** (array) - An array of budget objects, each containing id, groupId, and name. ### Response Example ```json { "data": [ { "id": "string", "groupId": "string", "name": "string" } ] } ``` ``` -------------------------------- ### Route Development Pattern with Middleware Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Middleware.md Illustrates the recommended pattern for developing new routes that utilize the pre-initialized budget instance. It shows how to access res.locals.budget and handle potential errors. ```javascript module.exports = (router) => { /** * @swagger * ...route documentation... */ router.get('/budgets/:budgetSyncId/path', async (req, res, next) => { try { // res.locals.budget is already initialized const data = await res.locals.budget.getAccounts(); res.json({ data }); } catch (err) { // Pass to error handler next(err); } }); // Error handler will: // 1. Check error message patterns // 2. Determine appropriate HTTP status code // 3. Return formatted error response // 4. Log the error }; ``` -------------------------------- ### GET /budgets/{budgetSyncId}/months/{month}/categories/{categoryId} Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns category budget information for a specific month. ```APIDOC ## GET /budgets/{budgetSyncId}/months/{month}/categories/{categoryId} ### Description Returns category budget information for a specific month. ### Method GET ### Endpoint /budgets/{budgetSyncId}/months/{month}/categories/{categoryId} ### Response #### Success Response (200) - **data** (object) - Category budget information. - **id** (string) - **name** (string) - **is_income** (boolean) - **hidden** (boolean) - **group_id** (string) - **budgeted** (integer) - **spent** (integer) - **balance** (integer) ### Response Example ```json { "data": { "id": "string", "name": "string", "is_income": boolean, "hidden": boolean, "group_id": "string", "budgeted": integer, "spent": integer, "balance": integer } } ``` ``` -------------------------------- ### Get Category Notes Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves notes associated with a specific category. Useful for adding context or details to categories. ```javascript const notes = await budget.getCategoryNotes("category-id"); ``` -------------------------------- ### Add Transaction Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Manually adds a new transaction to an account. Use this for recording expenses or income. ```javascript await budget.addTransaction("account-id", { // transaction details }); ``` -------------------------------- ### Add Budget Transfer Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Records a transfer between categories within the budget. Use this for moving funds between different budget areas. ```javascript await budget.addCategoryTransfer("from-category-id", "to-category-id", amount); ``` -------------------------------- ### Get Specific Month Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Retrieves a single month's data by its ID. Use this when you need details for a particular month. ```javascript const month = await budget.getMonth("month-id"); ``` -------------------------------- ### Create Budget Instance Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Initializes a new budget instance using a synchronization ID and an optional password for encrypted budgets. Downloads the budget if not cached locally. The password is only required on the first access for encrypted budgets. ```javascript async function Budget(budgetSyncId, budgetEncryptionPassword) const budget = await Budget('abc-123-sync-id', 'optional-password'); const accounts = await budget.getAccounts(); ``` -------------------------------- ### Initialize Budget Module Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/README.md Instantiate the Budget module using the sync ID and encryption password. This module provides methods for budget operations. ```javascript const { Budget } = require('./src/v1/budget'); // Usage const budget = await Budget(syncId, encryptionPassword); const accounts = await budget.getAccounts(); ``` -------------------------------- ### Per-Request Budget Initialization Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ARCHITECTURE.md This snippet details the initialization process for a budget when a request arrives. It shows how the budget loader middleware prepares the budget object for use in route handlers and how the Actual client is managed for subsequent requests. ```javascript // When request arrives for /budgets/{syncId}/... // 1. Budget loader middleware const budget = await Budget(syncId, encryptionPassword); res.locals.budget = budget; // Behind the scenes: // - getActualApiClient() initializes if needed // - actualApi.downloadBudget(syncId) loads budget from server // - Creates mapping of syncId to budgetId // - Returns budget object with all methods // 2. Route handler calls methods on budget const accounts = await res.locals.budget.getAccounts(); // 3. After response sent, budget remains loaded // - Actual client reused for next request with same syncId // - Auto-shuts down after 1 hour of no activity ``` -------------------------------- ### GET /budgets/{budgetSyncId}/accounts/{accountId}/balancehistory Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves the historical balance for an account within a specified date range with daily granularity. Requires a start date and optionally accepts an end date. ```APIDOC ## GET /budgets/{budgetSyncId}/accounts/{accountId}/balancehistory ### Description Gets the balance history for an account from start to end date with daily granularity. ### Method GET ### Endpoint /v1/budgets/{budgetSyncId}/accounts/{accountId}/balancehistory ### Parameters #### Path Parameters - **budgetSyncId** (string) - Required - Synchronization ID from Actual Budget - **accountId** (string) - Required - The ID of the account #### Query Parameters - **since_date** (string) - Required - YYYY-MM-DD format - **until_date** (string) - Optional - YYYY-MM-DD format. Defaults to today. #### Header Parameters - **budget-encryption-password** (string) - Optional - Encryption password for encrypted budgets ### Response #### Success Response (200) - **data** (object) - An object where keys are dates (YYYY-MM-DD) and values are the balance for that day. #### Response Example ```json { "data": { "2023-08-01": 2000, "2023-08-02": 1950, "2023-08-03": 2100 } } ``` ``` -------------------------------- ### Date Range Calculation Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Utilities.md Calculates and formats dates for use in API requests or data retrieval. It provides examples for getting the current local date and a date from 30 days prior, formatted as ISO strings. ```javascript const { currentLocalDate, formatDateToISOString } = require('../utils/utils'); // Get today's balance const today = currentLocalDate(); const todayStr = formatDateToISOString(today); // Get balance 30 days ago const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000); const thirtyDaysAgoStr = formatDateToISOString(thirtyDaysAgo); ``` -------------------------------- ### Actual API Client Configuration Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/CONFIGURATION.md Illustrates the parameters required for initializing the Actual API client. The client automatically shuts down and reinitializes hourly. ```javascript // src/v1/actual-client-provider.js // ... const client = new ActualClient({ dataDir: process.env.ACTUAL_DATA_DIR, serverURL: 'http://localhost:5007', password: 'your-password' }); // ... ``` -------------------------------- ### Get Available Budgets Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves a list of available budgets on the server. This endpoint is experimental and requires access to the Actual data directory. ```json { "data": [ { "id": "string", "groupId": "string", "name": "string" } ] } ``` -------------------------------- ### Get Account Balance History Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves the historical balance of an account over a specified date range with daily granularity. Requires a start date and optionally accepts an end date. Supports optional encryption password. ```json { "data": { "2023-08-01": 2000, "2023-08-02": 1950, "2023-08-03": 2100 } } ``` -------------------------------- ### Get Specific Budget Category Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Retrieves a single category by its ID. Use this to get detailed information about a specific category. ```javascript async getCategory(categoryId) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/jhonderson/actual-http-api/blob/main/README.md Execute the project's unit tests using npm. ```bash npm test ``` -------------------------------- ### Data Directory Structure Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/CONFIGURATION.md Shows the organization of budget data within the ACTUAl_DATA_DIR. Each budget has its own directory containing a SQLite database and metadata. ```treeview data/ ├── budget-id-1/ │ ├── db.sqlite │ ├── metadata.json │ └── ... ├── budget-id-2/ │ ├── db.sqlite │ ├── metadata.json │ └── ... └── ... ``` -------------------------------- ### Import Transactions Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Imports multiple transactions into an account, typically from a file or external source. Useful for bulk data entry. ```javascript await budget.importTransactions("account-id", [ // array of transaction objects ]); ``` -------------------------------- ### Get Budget Months List Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves a list of months associated with a specific budget. Use this endpoint to get an overview of available budget periods. ```json { "data": ["2023-07", "2023-08", "2023-09"] } ``` -------------------------------- ### runQuery Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Executes an Actual Query Language (AQL) query against the budget database. The `q` object is available on the budget instance for query construction. ```APIDOC ## runQuery(query) ### Description Executes an Actual Query Language (AQL) query against the budget database. The `q` object is available on the budget instance for query construction. ### Parameters #### Path Parameters - **query** (string) - Yes - Actual Query Language (AQL) query ### Returns Promise ### Request Example ```javascript const results = await budget.runQuery( budget.q('transactions') .filter({ account: 'acct-id' }) .select(['date', 'amount']) ); ``` ``` -------------------------------- ### Get Specific Budget Month Category Group Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Fetches information for a specific category group within a month. Use this to get details about a particular group of categories. ```json { "data": { "id": "string", "name": "string", "is_income": boolean, "hidden": boolean, "categories": [] } } ``` -------------------------------- ### createAccount(account, initialBalance) Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Creates a new account with the provided details and an optional initial balance. Returns the newly created account object. ```APIDOC ## createAccount(account, initialBalance) ### Description Creates a new account. ### Method POST ### Endpoint /accounts ### Parameters #### Request Body - **account** (object) - Yes - Account object - **name** (string) - Yes - Account name - **offbudget** (boolean) - No - Off-budget flag - **initialBalance** (integer) - No - Initial balance in cents ### Returns Promise - Created account object ``` -------------------------------- ### Get Account Balance Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Fetches the current balance for a specific account. An optional cutoff date can be provided to get the balance as of that date. Supports optional encryption password. ```json { "data": 2000 } ``` -------------------------------- ### Deploy Actual HTTP API Service on Fly.io Source: https://github.com/jhonderson/actual-http-api/blob/main/examples/USAGE_EXAMPLES.md Example `fly.toml` configuration for deploying the Actual HTTP API service as a Docker container on Fly.io. Requires setting `ACTUAL_SERVER_PASSWORD` and `API_KEY` as secrets in the Fly console. ```toml [build] dockerfile = "Dockerfile" [env] # Set these in your Fly.io secrets # ACTUAL_SERVER_PASSWORD = "..." # API_KEY = "..." [[services]] internal_port = 8080 processes = ["app"] [services.concurrency] max_per_instance = 1 prevent_க்கம்_over_1 = true [services.http_options] response.compress_ விகிதம் = true [services.tcp_checks] interval = "30s" timeout = "4s" ``` -------------------------------- ### Environment File (.env) Configuration Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/CONFIGURATION.md Create a .env file for local development to specify port, node environment, server URLs, passwords, API keys, and optional Swagger configuration. ```env PORT=5007 NODE_ENV=development ACTUAL_SERVER_URL=http://localhost:5006/ ACTUAL_SERVER_PASSWORD=your-actual-password API_KEY=your-api-key ACTUAL_DATA_DIR=./data # Optional: Swagger configuration for local access SWAGGER_PROTOCOL=http SWAGGER_HOST=localhost SWAGGER_PORT=5007 ``` -------------------------------- ### Get All Payees Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Fetches a list of all payees. ```javascript async getPayees() ``` -------------------------------- ### GET /actualhttpapiversion Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves the version of the actual-http-api service. ```APIDOC ## GET /actualhttpapiversion ### Description Returns the version of the actual-http-api service. ### Method GET ### Endpoint /actualhttpapiversion ### Response #### Success Response (200) - **data** (string) - The version string of the service. ### Response Example ```json { "data": "26.6.1" } ``` ``` -------------------------------- ### BudgetInfo Object Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/TYPES.md Represents metadata about a budget on the server. Requires an internal ID, a sync ID for API access, and a display name. ```json { "id": "budget-internal-id", "groupId": "abc-123-sync-id", "name": "Personal Budget" } ``` -------------------------------- ### Create Account Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/README.md Use this POST request to create a new account. Provide the account name and its offbudget status in the JSON payload. ```bash # Create account curl -X POST -H "x-api-key: key" \ -H "Content-Type: application/json" \ -d '{"account":{"name":"Checking","offbudget":false}}' \ http://localhost:5007/v1/budgets/sync-id/accounts ``` -------------------------------- ### Make a Basic API Request Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/README.md Use curl to make a request to the API to retrieve accounts for a specific budget sync ID. Ensure you replace placeholders with your actual API key and sync ID. ```bash curl -H "x-api-key: your-api-key" \ http://localhost:5007/v1/budgets/{YOUR_SYNC_ID}/accounts ``` -------------------------------- ### Get Common Payees Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Fetches a list of the most frequently used payees. ```javascript async getCommonPayees() ``` -------------------------------- ### GET /budgets/{budgetSyncId}/payees/{payeeId} Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves information for a specific payee. ```APIDOC ## GET /budgets/{budgetSyncId}/payees/{payeeId} ### Description Returns payee information. ### Method GET ### Endpoint /budgets/{budgetSyncId}/payees/{payeeId} ### Response #### Success Response (200) ```json { "data": { "id": "string", "name": "string", "transfer_acct": "string (optional)" } } ``` ``` -------------------------------- ### POST /budgets/{budgetSyncId}/run-query Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/TYPES.md Executes a query against a specific budget using Actual Query Language (AQL) and returns the results. ```APIDOC ## POST /budgets/{budgetSyncId}/run-query ### Description Executes an Actual Query Language (AQL) query against a specified budget. ### Method POST ### Endpoint /budgets/{budgetSyncId}/run-query ### Parameters #### Path Parameters - **budgetSyncId** (string) - Required - The synchronization ID of the budget to query. #### Request Body - **query** (string) - Required - The AQL query string to execute. ### Response #### Success Response (200) - **data** (array) - The results of the AQL query. The structure of the data depends on the query itself. ### Response Example { "data": [ { "date": "2023-08-01", "amount": 5000 }, { "date": "2023-08-02", "amount": 3000 } ] } ``` -------------------------------- ### GET /budgets/{budgetSyncId}/payees Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns a list of all payees for a given budget. ```APIDOC ## GET /budgets/{budgetSyncId}/payees ### Description Returns list of all payees. ### Method GET ### Endpoint /budgets/{budgetSyncId}/payees ### Response #### Success Response (200) ```json { "data": [ { "id": "string", "name": "string", "transfer_acct": "string (optional)" } ] } ``` ``` -------------------------------- ### Get Category Information Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves detailed information for a specific category by its ID. ```json { "data": { "id": "string", "name": "string", "is_income": boolean, "hidden": boolean, "group_id": "string" } } ``` -------------------------------- ### Execute AQL Query Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Executes an Actual Query Language (AQL) query against the budget database. The `q` object is available for query construction. ```javascript async runQuery(query) ``` -------------------------------- ### Get Actual HTTP API Version Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Fetches the current version of the actual-http-api service. ```json { "data": "26.6.1" } ``` -------------------------------- ### Execute AQL Query Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Executes an Actual Query Language (AQL) query against the budget database. The 'q' object is available for query construction. ```json { "query": "AQL query string" } ``` ```json { "data": [...] } ``` -------------------------------- ### Create Directory If It Does Not Exist Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Utilities.md Use this function to ensure a directory and its parent directories exist. It takes a directory path as a string. ```javascript function createDirIfDoesNotExist(dir) // Creates ./data and ./data/budgets if they don't exist ``` ```javascript createDirIfDoesNotExist('./data/budgets'); ``` -------------------------------- ### GET /budgets/{budgetSyncId}/tags Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns a list of all tags associated with a specific budget. ```APIDOC ## GET /budgets/{budgetSyncId}/tags ### Description Returns list of all tags. ### Method GET ### Endpoint /budgets/{budgetSyncId}/tags ### Response #### Success Response (200) - **data** (array) - A list of tag objects, each containing 'id' and 'name'. ### Response Example ```json { "data": [ { "id": "string", "name": "string" } ] } ``` ``` -------------------------------- ### GET /budgets/{budgetSyncId}/categorygroups Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns a list of all category groups for a given budget. ```APIDOC ## GET /budgets/{budgetSyncId}/categorygroups ### Description Returns list of all category groups. ### Method GET ### Endpoint /budgets/{budgetSyncId}/categorygroups #### Query Parameters - **hidden** (query, optional): Filter by hidden status ### Response #### Success Response (200) ```json { "data": [ { "id": "string", "name": "string", "is_income": boolean, "hidden": boolean, "categories": [] } ] } ``` ``` -------------------------------- ### GET /budgets/{budgetSyncId}/months/{month}/categories Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Returns all categories for a specific month. ```APIDOC ## GET /budgets/{budgetSyncId}/months/{month}/categories ### Description Returns all categories for a specific month. ### Method GET ### Endpoint /budgets/{budgetSyncId}/months/{month}/categories ### Response #### Success Response (200) - **data** (array) - A list of category objects. - **id** (string) - **name** (string) - **is_income** (boolean) - **hidden** (boolean) - **group_id** (string) - **budgeted** (integer) - **spent** (integer) - **balance** (integer) ### Response Example ```json { "data": [ { "id": "string", "name": "string", "is_income": boolean, "hidden": boolean, "group_id": "string", "budgeted": integer, "spent": integer, "balance": integer } ] } ``` ``` -------------------------------- ### Test Actual Server Connectivity Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ERRORS.md This curl command verifies that the service can connect to the Actual server. It sends a GET request to retrieve budget months. ```bash # Test Actual server connectivity curl -X GET "http://localhost:5007/v1/budgets/sync-id/months" ``` -------------------------------- ### Get All Schedules Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/api-reference/Budget.md Retrieves a list of all schedules. Use this to view all scheduled financial activities. ```javascript async getSchedules() ``` -------------------------------- ### Access Configuration Settings Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/README.md Import and access configuration settings, including the port, API key, and Actual server URL, which are parsed from environment variables. ```javascript const { config } = require('./src/config/config'); // Access configuration console.log(config.port); // 5007 console.log(config.apiKey); // API key from env console.log(config.actual.serverUrl); // Actual server URL ``` -------------------------------- ### GET /budgets Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/TYPES.md Retrieves a list of BudgetInfo objects, which represent metadata about budgets on the server. ```APIDOC ## GET /budgets ### Description Retrieves a list of budgets available on the server. ### Method GET ### Endpoint /budgets ### Parameters #### Query Parameters None ### Response #### Success Response (200) - **data** (BudgetInfo[]) - A list of budget information objects. ### Response Example { "data": [ { "id": "budget-internal-id", "groupId": "abc-123-sync-id", "name": "Personal Budget" } ] } ``` -------------------------------- ### Create Account Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Creates a new account within a budget. Requires account name, and optionally accepts offbudget status and initial balance. Returns the created account details. ```json { "account": { "name": "string (required)", "offbudget": boolean, "initialBalance": integer } } ``` ```json { "data": { "id": "string", "name": "string", "offbudget": boolean, "closed": boolean } } ``` -------------------------------- ### Server Info Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Methods to retrieve general server and budget information. ```APIDOC ## Server Info ### Description Provides access to general information about the server and available budgets. ### Methods - **getBudgets** - Description: Retrieves a list of all available budgets on the server. - Signature: `getBudgets()` - Usage Example: `const allBudgets = budget.getBudgets();` - **getServerVersion** - Description: Retrieves the current version of the server software. - Signature: `getServerVersion()` - Usage Example: `const version = budget.getServerVersion();` - **getIDByName** - Description: Retrieves the ID of a budget given its name. (3 methods total) - Signature: `getIDByName(budgetName)` - Parameters: - **budgetName** (string) - Required - The name of the budget. - Usage Example: `const budgetId = budget.getIDByName('Personal Budget');` ``` -------------------------------- ### Close Account Example Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Marks an account as closed. Use this when an account is no longer active. ```javascript await budget.closeAccount("account-id"); ``` -------------------------------- ### GET /budgets/{budgetSyncId}/id-by-name Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves the ID of an entity (account, category, or payee) by its name. ```APIDOC ## GET /budgets/{budgetSyncId}/id-by-name ### Description Retrieves the ID of an entity (account, category, payee) by name. ### Method GET ### Endpoint /budgets/{budgetSyncId}/id-by-name ### Parameters #### Path Parameters - **budgetSyncId** (string) - Required - The unique identifier for the budget synchronization. #### Query Parameters - **type** (string) - Required - Entity type (`account`, `category`, `payee`). - **name** (string) - Required - Name to search for. ### Response #### Success Response (200) - **data** (string) - The ID of the found entity. ### Response Example ```json { "data": "entity-id" } ``` ``` -------------------------------- ### Backup Actual Budget Data with Bash Script Source: https://github.com/jhonderson/actual-http-api/blob/main/examples/USAGE_EXAMPLES.md A bash script to back up your Actual budget. Ensure you update the ACTUAL_BUDGET_URL, ACTUAL_BUDGET_API_KEY, and ACTUAL_BUDGET_SYNC_ID_LIST variables before running. Grant execute permissions and run the script. ```bash ACTUAL_BUDGET_URL="..." ACTUAL_BUDGET_API_KEY="..." ACTUAL_BUDGET_SYNC_ID_LIST=("...") ``` ```bash chmod +x budget_backup.sh ./budget_backup.sh ``` -------------------------------- ### GET /budgets/{budgetSyncId}/tags/{tagId} Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/ENDPOINTS.md Retrieves information for a specific tag within a budget. ```APIDOC ## GET /budgets/{budgetSyncId}/tags/{tagId} ### Description Returns tag information. ### Method GET ### Endpoint /budgets/{budgetSyncId}/tags/{tagId} ### Response #### Success Response (200) - **data** (object) - An object containing the tag's 'id' and 'name'. - **id** (string) - The unique identifier of the tag. - **name** (string) - The name of the tag. ### Response Example ```json { "data": { "id": "string", "name": "string" } } ``` ``` -------------------------------- ### Budget Loading Middleware Source: https://github.com/jhonderson/actual-http-api/blob/main/_autodocs/INDEX.md Initializes the Budget instance for a request. This middleware ensures the Budget object is available for subsequent route handlers. ```javascript app.use(budgetLoadingMiddleware); ```