Developer Guide: Integrating BankStatementFlow API into Your Applications

BankStatementFlow Team

Integrating AI-powered document processing into your applications can transform user experience and operational efficiency. This comprehensive guide walks developers through implementing BankStatementFlow's API, from authentication to advanced features.

Getting Started with the API

Authentication

BankStatementFlow uses API key authentication with optional OAuth 2.0 for enhanced security:


                // Basic API Key Authentication
                const headers = {
                    'Authorization': 'Bearer YOUR_API_KEY',
                    'Content-Type': 'application/json'
                };

                // OAuth 2.0 Authentication
                const tokenResponse = await fetch('https://api.bankstatementflow.com/oauth/token', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        grant_type: 'client_credentials',
                        client_id: 'YOUR_CLIENT_ID',
                        client_secret: 'YOUR_CLIENT_SECRET'
                    })
                });
                

Base URL and Versioning

All API endpoints use the base URL: https://api.bankstatementflow.com/v1/

The API uses semantic versioning with backwards compatibility guaranteed within major versions.

Core API Endpoints

Document Upload and Processing

The primary endpoint for document processing:


                POST /documents/process

                // Example request
                const formData = new FormData();
                formData.append('file', fileInput.files[0]);
                formData.append('document_type', 'bank_statement');
                formData.append('output_format', 'json');

                const response = await fetch('https://api.bankstatementflow.com/v1/documents/process', {
                    method: 'POST',
                    headers: { 'Authorization': 'Bearer YOUR_API_KEY' },
                    body: formData
                });

                const result = await response.json();
                console.log(result.extracted_data);
                

Asynchronous Processing

For large documents, use asynchronous processing:


                // Submit document for processing
                POST /documents/submit
                {
                    "file_url": "https://example.com/document.pdf",
                    "document_type": "bank_statement",
                    "webhook_url": "https://yourapp.com/webhooks/processing-complete"
                }

                // Response
                {
                    "job_id": "job_123456789",
                    "status": "processing",
                    "estimated_completion": "2025-06-12T14:30:00Z"
                }

                // Check status
                GET /documents/status/job_123456789
                

Response Formats and Data Structure

Standard Response Format


                {
                    "success": true,
                    "data": {
                        "document_id": "doc_abc123",
                        "document_type": "bank_statement",
                        "processing_time": 2.3,
                        "confidence_score": 0.987,
                        "extracted_data": {
                            "account_number": "****1234",
                            "statement_period": {
                                "start_date": "2025-05-01",
                                "end_date": "2025-05-31"
                            },
                            "transactions": [
                                {
                                    "date": "2025-05-15",
                                    "description": "Online Purchase",
                                    "amount": -45.67,
                                    "balance": 1234.56,
                                    "category": "retail"
                                }
                            ]
                        }
                    },
                    "metadata": {
                        "pages_processed": 3,
                        "total_transactions": 47
                    }
                }
                

Error Handling


                // Error response format
                {
                    "success": false,
                    "error": {
                        "code": "INVALID_DOCUMENT_TYPE",
                        "message": "Unsupported document type",
                        "details": "Only PDF and image files are supported"
                    }
                }

                // JavaScript error handling
                try {
                    const response = await processDocument(file);
                    if (!response.success) {
                        handleError(response.error);
                    } else {
                        handleSuccess(response.data);
                    }
                } catch (error) {
                    console.error('Network error:', error);
                }
                

Advanced Features

Custom Field Extraction

Define custom fields for specialized document types:


                POST /documents/process
                {
                    "file": "base64_encoded_file",
                    "document_type": "custom",
                    "custom_fields": [
                        {
                            "name": "customer_id",
                            "type": "string",
                            "pattern": "CUST-\d{6}",
                            "required": true
                        },
                        {
                            "name": "total_amount",
                            "type": "currency",
                            "validation": "positive"
                        }
                    ]
                }
                

Batch Processing

Process multiple documents in a single API call:


                POST /documents/batch-process
                {
                    "documents": [
                        {
                            "file_url": "https://example.com/doc1.pdf",
                            "document_type": "invoice"
                        },
                        {
                            "file_url": "https://example.com/doc2.pdf",
                            "document_type": "receipt"
                        }
                    ],
                    "webhook_url": "https://yourapp.com/webhooks/batch-complete"
                }
                

Data Validation and Enrichment

Enable additional validation and data enrichment:


                POST /documents/process
                {
                    "file": "base64_encoded_file",
                    "document_type": "bank_statement",
                    "options": {
                        "validate_calculations": true,
                        "enrich_categories": true,
                        "detect_duplicates": true,
                        "confidence_threshold": 0.95
                    }
                }
                

Integration Patterns

Webhook Implementation

Set up webhooks for real-time processing notifications:


                // Webhook endpoint implementation (Node.js/Express)
                app.post('/webhooks/processing-complete', (req, res) => {
                    const { job_id, status, data } = req.body;

                    if (status === 'completed') {
                        // Process the extracted data
                        updateDatabase(job_id, data.extracted_data);
                        notifyUser(job_id, 'Document processed successfully');
                    } else if (status === 'failed') {
                        // Handle processing failure
                        logError(job_id, data.error);
                        notifyUser(job_id, 'Document processing failed');
                    }

                    res.status(200).send('OK');
                });
                

Client-Side Integration

Implement secure client-side document upload:


                // React component example
                import React, { useState } from 'react';

                function DocumentProcessor() {
                    const [processing, setProcessing] = useState(false);
                    const [result, setResult] = useState(null);

                    const handleFileUpload = async (file) => {
                        setProcessing(true);

                        try {
                            const formData = new FormData();
                            formData.append('file', file);

                            const response = await fetch('/api/process-document', {
                                method: 'POST',
                                body: formData
                            });

                            const data = await response.json();
                            setResult(data);
                        } catch (error) {
                            console.error('Processing failed:', error);
                        } finally {
                            setProcessing(false);
                        }
                    };

                    return (
                        
handleFileUpload(e.target.files[0])} disabled={processing} /> {processing &&

Processing document...

} {result &&
{JSON.stringify(result, null, 2)}
}
); }

SDK and Libraries

Official SDKs

BankStatementFlow provides official SDKs for popular languages:


                // JavaScript/Node.js
                npm install bankstatementflow-sdk

                const BankStatementFlow = require('bankstatementflow-sdk');
                const client = new BankStatementFlow('YOUR_API_KEY');

                const result = await client.processDocument({
                    file: fileBuffer,
                    documentType: 'bank_statement'
                });

                // Python
                pip install bankstatementflow-python

                from bankstatementflow import Client

                client = Client(api_key='YOUR_API_KEY')
                result = client.process_document(
                    file_path='document.pdf',
                    document_type='bank_statement'
                )
                

Third-Party Integrations

Popular integration examples:


                // Zapier Integration
                const zapierWebhook = async (extractedData) => {
                    await fetch('https://hooks.zapier.com/hooks/catch/...', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(extractedData)
                    });
                };

                // Slack Notification
                const notifySlack = async (status, documentType) => {
                    await fetch(process.env.SLACK_WEBHOOK_URL, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            text: `Document processing ${status}: ${documentType}`
                        })
                    });
                };
                

Security Best Practices

API Key Management

  • Store API keys in environment variables
  • Use different keys for development and production
  • Implement key rotation policies
  • Monitor API key usage and set alerts

Data Protection

  • Always use HTTPS for API calls
  • Implement request signing for sensitive operations
  • Validate webhook signatures
  • Use temporary URLs for file uploads when possible

Performance Optimization

Caching Strategies


                // Implement response caching
                const cache = new Map();

                const getCachedResult = (documentHash) => {
                    return cache.get(documentHash);
                };

                const setCachedResult = (documentHash, result) => {
                    cache.set(documentHash, result);
                    // Implement TTL and size limits
                };
                

Rate Limiting

Implement client-side rate limiting to avoid API limits:


                class RateLimiter {
                    constructor(maxRequests, timeWindow) {
                        this.maxRequests = maxRequests;
                        this.timeWindow = timeWindow;
                        this.requests = [];
                    }

                    async makeRequest(requestFunction) {
                        const now = Date.now();
                        this.requests = this.requests.filter(
                            time => now - time < this.timeWindow
                        );

                        if (this.requests.length >= this.maxRequests) {
                            const waitTime = this.timeWindow - (now - this.requests[0]);
                            await new Promise(resolve => setTimeout(resolve, waitTime));
                        }

                        this.requests.push(now);
                        return await requestFunction();
                    }
                }
                

Testing and Debugging

API Testing


                // Jest test example
                describe('BankStatementFlow API', () => {
                    test('processes bank statement successfully', async () => {
                        const testFile = fs.readFileSync('test-statement.pdf');

                        const result = await client.processDocument({
                            file: testFile,
                            documentType: 'bank_statement'
                        });

                        expect(result.success).toBe(true);
                        expect(result.data.extracted_data.transactions).toBeDefined();
                        expect(result.data.confidence_score).toBeGreaterThan(0.95);
                    });
                });
                

Error Monitoring

Implement comprehensive error monitoring:


                const monitorApiCall = async (apiFunction) => {
                    const startTime = Date.now();

                    try {
                        const result = await apiFunction();

                        // Log success metrics
                        logMetric('api_call_success', {
                            duration: Date.now() - startTime,
                            endpoint: apiFunction.name
                        });

                        return result;
                    } catch (error) {
                        // Log error details
                        logError('api_call_failed', {
                            error: error.message,
                            endpoint: apiFunction.name,
                            duration: Date.now() - startTime
                        });

                        throw error;
                    }
                };
                

This comprehensive guide provides the foundation for integrating BankStatementFlow's API into your applications. The API's flexibility and robust feature set enable developers to build sophisticated document processing workflows that scale with business needs.

Related Articles

Bank Statement Analysis: Best Practices for Financial Data Management

Learn the essential best practices for analyzing bank statements efficiently and securely.

Read More

Data Security in Financial Document Processing

Understanding the critical importance of data security when processing sensitive financial documents.

Read More