FMP Node API Documentation
Helper Utilities
The FMP Node Wrapper includes a comprehensive set of helper utilities to enhance your development experience, provide better error handling, and simplify common financial data processing tasks.
Available Helper Categories
API Exploration Helpers (FMPHelpers
)
Discover and explore the available API methods at runtime.
1import { FMP, FMPHelpers } from 'fmp-node-api';
2
3const fmp = new FMP(); // Uses FMP_API_KEY environment variable
4
5// Get all endpoint categories
6const categories = FMPHelpers.getEndpointCategories(fmp);
7console.log('Available endpoints:', categories);
8// Output: ['stock', 'financial', 'quote', 'market', ...]
9
10// Get methods for a specific endpoint
11const stockMethods = FMPHelpers.getEndpointMethods(fmp, 'stock');
12console.log('Stock methods:', stockMethods);
13// Output: ['getQuote', 'getMarketCap', 'getStockSplits', ...]
14
15// Get comprehensive API summary
16const summary = FMPHelpers.getApiSummary(fmp);
17console.log('API Summary:', summary);
18// Output: { totalEndpoints: 15, totalMethods: 45, categories: [...], methodCounts: {...} }
19
20// Check if a method exists
21const hasMethod = FMPHelpers.hasMethod(fmp, 'stock', 'getQuote');
22console.log('Has getQuote method:', hasMethod); // true
23
24// Get method information
25const methodInfo = FMPHelpers.getMethodInfo(fmp, 'stock', 'getQuote');
26console.log('Method info:', methodInfo);
27// Output: { name: 'getQuote', type: 'function', async: true }
Validation Helpers (FMPValidation
)
Validate parameters and API responses with comprehensive error checking.
1import { FMPValidation } from 'fmp-node-api';
2
3// Validate symbols
4FMPValidation.isValidSymbol('AAPL'); // true
5FMPValidation.isValidSymbol('aapl'); // false (must be uppercase)
6FMPValidation.isValidCryptoSymbol('BTCUSD'); // true
7FMPValidation.isValidForexPair('EURUSD'); // true
8
9// Validate dates
10FMPValidation.isValidDate('2024-01-15'); // true
11FMPValidation.isValidDate('2024-13-01'); // false (invalid month)
12FMPValidation.isValidDateRange('2024-01-01', '2024-01-31'); // true
13
14// Validate API responses
15const response = { success: true, data: [] };
16FMPValidation.isValidResponse(response); // true
17
18// Validate API keys
19FMPValidation.isValidApiKey('your-32-character-api-key'); // true
20
21// Comprehensive parameter validation
22const quoteParams = { symbol: 'AAPL', from: '2024-01-01', to: '2024-01-31' };
23const errors = FMPValidation.validateQuoteParams(quoteParams);
24if (errors.length > 0) {
25console.error('Validation errors:', errors);
26}
27
28// Throw validation errors
29FMPValidation.throwIfInvalid(errors, 'Quote Parameters');
Utility Helpers (FMPUtils
)
Format and process financial data with common utilities.
1import { FMPUtils } from 'fmp-node-api';
2
3// Format currency values
4FMPUtils.formatCurrency(1234.56); // '$1,234.56'
5FMPUtils.formatCurrency(1234.56, 'EUR'); // '€1,234.56'
6FMPUtils.formatCurrency(1234.56, 'GBP', 'en-GB'); // '£1,234.56'
7
8// Format percentages
9FMPUtils.formatPercentage(0.15); // '15.00%'
10FMPUtils.formatPercentage(0.1234, 1); // '12.3%'
11
12// Format large numbers
13FMPUtils.formatLargeNumber(1000); // '1.0K'
14FMPUtils.formatLargeNumber(1500000); // '1.5M'
15FMPUtils.formatLargeNumber(2000000000); // '2.0B'
16FMPUtils.formatLargeNumber(3000000000000); // '3.0T'
17
18// Date utilities
19const date = FMPUtils.parseDate('2024-01-15');
20FMPUtils.formatDate(date, 'short'); // 'Jan 15, 2024'
21FMPUtils.formatDate(date, 'long'); // 'Monday, January 15, 2024'
22FMPUtils.formatDate(date, 'iso'); // '2024-01-15'
23
24// Calculate working days
25FMPUtils.getWorkingDays('2024-01-15', '2024-01-19'); // 5 (Monday to Friday)
26
27// Calculate percentage change
28FMPUtils.calculatePercentageChange(100, 120); // 20 (20% increase)
29
30// Batch API calls with rate limiting
31const calls = [
32() => fmp.quote.getQuote({ symbol: 'AAPL' }),
33() => fmp.quote.getQuote({ symbol: 'GOOGL' }),
34() => fmp.quote.getQuote({ symbol: 'MSFT' })
35];
36
37const results = await FMPUtils.batchCalls(calls, 100); // 100ms delay between calls
38
39// Retry with exponential backoff
40const result = await FMPUtils.retryWithBackoff(
41() => fmp.quote.getQuote({ symbol: 'AAPL' }),
423, // max retries
431000 // base delay
44);
45
46// Debounce and throttle functions
47const debouncedFn = FMPUtils.debounce(() => console.log('Debounced'), 300);
48const throttledFn = FMPUtils.throttle(() => console.log('Throttled'), 1000);
Debug Helpers (FMPDebug
)
Enhanced debugging and development tools.
1import { FMP, FMPDebug } from 'fmp-node-api';
2
3const fmp = new FMP(); // Uses FMP_API_KEY environment variable
4
5// Enable debug mode
6FMPDebug.enableDebugMode();
7
8// Get API statistics
9const stats = FMPDebug.getApiStats(fmp);
10console.log('API Stats:', stats);
11
12// Validate API key
13const keyValidation = FMPDebug.validateApiKey('your-api-key');
14console.log('API Key validation:', keyValidation);
15
16// Check environment setup
17const envCheck = FMPDebug.checkApiKeyEnvironment();
18console.log('Environment check:', envCheck);
19
20// Get performance information
21const performance = FMPDebug.getPerformanceInfo();
22console.log('Performance:', performance);
23
24// Print comprehensive debug information
25FMPDebug.printDebugInfo(fmp);
26
27// Create debug wrapper for automatic logging
28const debugFmp = FMPDebug.createDebugWrapper(fmp);
29// All API calls will now be logged automatically
30
31// Log specific API calls
32FMPDebug.logApiCall('quote.getQuote', { symbol: 'AAPL' }, { success: true }, 150);
33FMPDebug.logApiError('quote.getQuote', { symbol: 'INVALID' }, new Error('Symbol not found'));
Environment Variables
The debug helpers support the following environment variables:
FMP_DEBUG=true
- Enable debug modeNODE_ENV=development
- Enable development logging
Error Handling with Helpers
Combine validation and error handling for robust applications:
1import { FMP, FMPValidation, FMPUtils } from 'fmp-node-api';
2
3async function getStockQuote(symbol: string) {
4// Validate input
5const errors = FMPValidation.validateQuoteParams({ symbol });
6FMPValidation.throwIfInvalid(errors, 'Stock Quote Parameters');
7
8try {
9const fmp = new FMP(); // Uses FMP_API_KEY environment variable
10const response = await fmp.quote.getQuote({ symbol });
11
12 if (!FMPValidation.isValidResponse(response)) {
13 throw new Error('Invalid API response');
14 }
15
16 if (response.success && response.data) {
17 const quote = response.data[0];
18 return {
19 symbol: quote.symbol,
20 price: FMPUtils.formatCurrency(quote.price),
21 change: FMPUtils.formatCurrency(quote.change),
22 changePercent: FMPUtils.formatPercentage(quote.changesPercentage / 100)
23 };
24 } else {
25 throw new Error(response.error || 'Unknown error');
26 }
27
28} catch (error) {
29console.error('Error fetching quote:', error);
30throw error;
31}
32}
33
34// Usage
35const formattedQuote = await getStockQuote('AAPL');
36console.log(formattedQuote);
37// Output: { symbol: 'AAPL', price: '$150.25', change: '$2.15', changePercent: '1.45%' }
Batch Processing Example
Use utilities for efficient batch processing:
1import { FMP, FMPUtils, FMPValidation } from 'fmp-node-api';
2
3async function analyzeMultipleStocks(symbols: string[]) {
4const fmp = new FMP(); // Uses FMP_API_KEY environment variable
5
6// Validate all symbols
7const invalidSymbols = symbols.filter(s => !FMPValidation.isValidSymbol(s));
8if (invalidSymbols.length > 0) {
9throw new Error(`Invalid symbols: ${invalidSymbols.join(', ')}`);
10}
11
12// Create batch calls
13const calls = symbols.map(symbol =>
14() => fmp.quote.getQuote({ symbol })
15);
16
17// Execute with rate limiting
18const results = await FMPUtils.batchCalls(calls, 100);
19
20// Process results
21return results.map((response, index) => {
22if (response.success && response.data) {
23const quote = response.data[0];
24return {
25symbol: quote.symbol,
26price: FMPUtils.formatCurrency(quote.price),
27marketCap: FMPUtils.formatLargeNumber(quote.marketCap),
28volume: FMPUtils.formatLargeNumber(quote.volume)
29};
30} else {
31return {
32symbol: symbols[index],
33error: response.error
34};
35}
36});
37}
38
39// Usage
40const analysis = await analyzeMultipleStocks(['AAPL', 'GOOGL', 'MSFT', 'TSLA']);
41console.table(analysis);
Best Practices
- Use validation helpers to catch errors early and provide better error messages
- Format data consistently using utility helpers for better user experience
- Enable debug mode during development for better troubleshooting
- Use batch processing for multiple API calls to respect rate limits
- Implement retry logic for transient failures using retry helpers
Type Safety
All helper utilities are fully typed and provide excellent TypeScript support:
1import { FMP, FMPHelpers, FMPValidation, FMPUtils, FMPDebug } from 'fmp-node-api';
2
3// All helpers provide full type safety
4const categories: string[] = FMPHelpers.getEndpointCategories(fmp);
5const isValid: boolean = FMPValidation.isValidSymbol('AAPL');
6const formatted: string = FMPUtils.formatCurrency(1234.56);
7const debugMode: boolean = FMPDebug.isDebugMode();
The helper utilities enhance the FMP Node Wrapper with powerful tools for validation, formatting, debugging, and API exploration while maintaining the library's TypeScript-first approach.