SECTION 1: LEARNING OBJECTIVES
By the end of this lesson, you will be able to:
-
Understand the concept of API banking and its role in digital banking.
-
Define Open Banking and its regulatory drivers (PSD2, etc.).
-
Identify the key API types in banking – internal, partner, and public APIs.
-
Design API-first banking platforms for digital banking.
-
Implement API security – authentication, authorisation, encryption.
-
Understand the business models of open banking.
-
Measure API performance using key metrics.
-
Develop an API strategy for a digital bank.
SECTION 2: WHAT IS API BANKING?
2.1 Definition
API Banking is the use of Application Programming Interfaces (APIs) to enable secure, standardised access to banking services, data, and capabilities for internal use, partners, and third-party developers.
2.2 The API Banking Value Chain
┌─────────────────────────────────────────────────────────────────────────────┐ │ API BANKING VALUE CHAIN │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────────────────────────────────────────────────────────────┐ │ │ │ CORE BANKING │ │ │ │ Accounts, Payments, Loans, Cards, KYC │ │ │ └──────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ v │ │ ┌──────────────────────────────────────────────────────────────────────┐ │ │ │ API GATEWAY │ │ │ │ Authentication, Authorisation, Rate Limiting, Monitoring │ │ │ └──────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ v │ │ ┌──────────────────────────────────────────────────────────────────────┐ │ │ │ API CHANNELS │ │ │ │ Internal APIs | Partner APIs | Public APIs (Open Banking) │ │ │ └──────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ v │ │ ┌──────────────────────────────────────────────────────────────────────┐ │ │ │ CONSUMERS │ │ │ │ Mobile Apps, Web Apps, Partners, Fintechs, Developers │ │ │ └──────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘
2.3 API Types in Banking
| Type | Description | Example | Audience |
|---|---|---|---|
| Internal APIs | For internal use within the bank. | Core system integration. | Internal developers. |
| Partner APIs | For specific partners. | Payment gateways, aggregators. | Trusted partners. |
| Public APIs (Open Banking) | For third-party developers. | Account information, payment initiation. | External developers. |
SECTION 3: OPEN BANKING
3.1 What is Open Banking?
Open Banking is a regulatory framework that requires banks to share customer data (with customer consent) with authorised third-party providers (TPPs) via secure APIs.
3.2 Key Open Banking Regulations
| Regulation | Region | Requirements | Timeline |
|---|---|---|---|
| PSD2 | EU | Payment initiation, account information. | 2018 |
| Open Banking | UK | Standardised APIs, TPP access. | 2018 |
| CDR (Consumer Data Right) | Australia | Open banking, open data. | 2019 |
| CCPA (California) | US | Data access rights. | 2020 |
| Canada | Canada | Consumer-driven banking. | 2023+ |
3.3 Open Banking Participants
┌─────────────────────────────────────────────────────────────────────────────┐ │ OPEN BANKING ECOSYSTEM │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────────────────────────────────────────────────────────────┐ │ │ │ CUSTOMER │ │ │ │ (Data owner, consents to data sharing) │ │ │ └──────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ v │ │ ┌──────────────────────────────────────────────────────────────────────┐ │ │ │ BANK (ASPSP) │ │ │ │ (Account Servicing Payment Service Provider) │ │ │ └──────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ v │ │ ┌──────────────────────────────────────────────────────────────────────┐ │ │ │ THIRD-PARTY PROVIDER (TPP) │ │ │ │ • AISP (Account Information Service Provider) │ │ │ │ • PISP (Payment Initiation Service Provider) │ │ │ └──────────────────────────────────────────────────────────────────────┘ │ │ │ │ │ v │ │ ┌──────────────────────────────────────────────────────────────────────┐ │ │ │ API PLATFORM │ │ │ │ (Secure, standardised APIs) │ │ │ └──────────────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────────────┘
SECTION 4: API DESIGN AND ARCHITECTURE
4.1 API Design Principles
| Principle | Description | Implementation |
|---|---|---|
| RESTful | Use REST architecture. | HTTP methods, resource URLs. |
| Standardised | Consistent design patterns. | OpenAPI/Swagger specifications. |
| Secure | Authentication and authorisation. | OAuth 2.0, OpenID Connect. |
| Scalable | Handle high volumes. | Rate limiting, caching. |
| Documented | Clear, comprehensive documentation. | Interactive API docs. |
| Versioned | Manage changes without breaking clients. | API versioning. |
| Monitored | Track performance and usage. | Analytics, dashboards. |
4.2 API Architecture Layers
| Layer | Description | Components |
|---|---|---|
| Presentation | API endpoints. | REST endpoints, GraphQL. |
| Business Logic | Core banking functions. | Transaction processing, validation. |
| Data Access | Data retrieval and storage. | Database, caching, ORM. |
| Integration | External systems. | Legacy systems, third-party APIs. |
4.3 Common Banking APIs
| API | Description | Use Case |
|---|---|---|
| Accounts API | Account information. | Balance, transaction history. |
| Payments API | Payment initiation. | Transfers, bill payments. |
| Cards API | Card management. | Activate, block, manage limits. |
| Customers API | Customer information. | Profile, KYC status. |
| Products API | Product information. | Loan rates, account types. |
| Transactions API | Transaction data. | History, search. |
| Notifications API | Alerts and messages. | Push notifications, emails. |
SECTION 5: API SECURITY
5.1 Security Framework
| Layer | Security Measures | Description |
|---|---|---|
| Network | TLS, VPN, WAF | Secure communication. |
| Application | Authentication, Authorisation | OAuth 2.0, OIDC. |
| API | Rate limiting, API keys | Prevent abuse. |
| Data | Encryption, masking | Protect sensitive data. |
| Monitoring | Logging, alerts | Detect threats. |
5.2 OAuth 2.0 Flow in Banking
┌─────────────────────────────────────────────────────────────────────────────┐ │ OAUTH 2.0 FLOW IN BANKING │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ 1. Customer consents to share data with TPP. │ │ │ │ 2. TPP requests access token from bank. │ │ │ │ 3. Bank authenticates customer and validates consent. │ │ │ │ 4. Bank issues access token to TPP. │ │ │ │ 5. TPP uses access token to call bank APIs. │ │ │ │ 6. Bank validates token and returns data. │ │ │ └─────────────────────────────────────────────────────────────────────────────┘
SECTION 6: IMPLEMENTATION IN PYTHON – API BANKING SIMULATION
# =================================================================== # MODULE 3, LESSON 8: API BANKING AND OPEN BANKING PLATFORMS # =================================================================== import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import json import hashlib import time from datetime import datetime, timedelta import warnings warnings.filterwarnings('ignore') print("="*70) print("API BANKING AND OPEN BANKING PLATFORMS") print("="*70) # ---------------------------------------------------------------- # PART A: API CATALOGUE # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART A: API Catalogue") print("-"*60) api_catalogue = pd.DataFrame({ 'API Name': [ 'Accounts API', 'Payments API', 'Transactions API', 'Cards API', 'Customers API', 'Products API', 'Notifications API', 'KYC API' ], 'Description': [ 'Account information and management.', 'Payment initiation and processing.', 'Transaction history and search.', 'Card management and authorisation.', 'Customer profile and authentication.', 'Product information and eligibility.', 'Notifications and alerts.', 'Know Your Customer verification.' ], 'Status': ['Active', 'Active', 'Active', 'Active', 'Active', 'Active', 'Beta', 'Beta'], 'Version': ['v1.0', 'v1.0', 'v1.0', 'v1.0', 'v1.0', 'v1.0', 'v0.9', 'v0.9'], 'API Type': ['Public', 'Public', 'Public', 'Partner', 'Internal', 'Public', 'Partner', 'Internal'], 'Rate Limit (req/min)': [100, 50, 100, 50, 25, 25, 25, 10] }) print("API Catalogue:") print(api_catalogue.to_string(index=False)) # ---------------------------------------------------------------- # PART B: OPEN BANKING ECOSYSTEM SIMULATION # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART B: Open Banking Ecosystem Simulation") print("-"*60) class OpenBankingPlatform: """Simulate an open banking platform.""" def __init__(self): self.customers = {} self.accounts = {} self.transactions = {} self.consents = {} self.third_party_apps = {} self.api_calls = [] def add_customer(self, customer_id, name, email): """Add a customer to the platform.""" self.customers[customer_id] = { 'id': customer_id, 'name': name, 'email': email, 'created': datetime.now().isoformat() } return customer_id def add_account(self, account_id, customer_id, account_type, balance): """Add an account for a customer.""" if customer_id not in self.customers: return {'error': 'Customer not found'} self.accounts[account_id] = { 'id': account_id, 'customer_id': customer_id, 'type': account_type, 'balance': balance, 'created': datetime.now().isoformat() } return account_id def register_third_party(self, app_id, name, description): """Register a third-party application.""" self.third_party_apps[app_id] = { 'id': app_id, 'name': name, 'description': description, 'registered': datetime.now().isoformat(), 'status': 'Active' } return app_id def grant_consent(self, customer_id, app_id, permissions): """Grant consent for a third-party app to access data.""" consent_key = f"{customer_id}:{app_id}" self.consents[consent_key] = { 'customer_id': customer_id, 'app_id': app_id, 'permissions': permissions, 'granted': datetime.now().isoformat(), 'status': 'Active' } return consent_key def check_consent(self, customer_id, app_id, required_permission): """Check if consent exists for a specific permission.""" consent_key = f"{customer_id}:{app_id}" if consent_key not in self.consents: return False, {'error': 'No consent found'} consent = self.consents[consent_key] if consent['status'] != 'Active': return False, {'error': 'Consent expired or revoked'} if required_permission not in consent['permissions']: return False, {'error': 'Permission not granted'} return True, None def get_accounts(self, customer_id, app_id): """API: Get customer accounts.""" # Check consent has_consent, error = self.check_consent(customer_id, app_id, 'view_accounts') if not has_consent: return error # Get accounts customer_accounts = [] for acc_id, acc in self.accounts.items(): if acc['customer_id'] == customer_id: customer_accounts.append({ 'account_id': acc_id, 'type': acc['type'], 'balance': acc['balance'] }) # Log API call self.api_calls.append({ 'api': 'Accounts API', 'customer_id': customer_id, 'app_id': app_id, 'timestamp': datetime.now().isoformat() }) return {'accounts': customer_accounts} def initiate_payment(self, customer_id, app_id, from_account, to_account, amount): """API: Initiate a payment.""" # Check consent has_consent, error = self.check_consent(customer_id, app_id, 'initiate_payments') if not has_consent: return error # Validate accounts if from_account not in self.accounts: return {'error': 'From account not found'} if to_account not in self.accounts: return {'error': 'To account not found'} # Check balance if self.accounts[from_account]['balance'] < amount: return {'error': 'Insufficient funds'} # Execute payment self.accounts[from_account]['balance'] -= amount self.accounts[to_account]['balance'] += amount # Log API call self.api_calls.append({ 'api': 'Payments API', 'customer_id': customer_id, 'app_id': app_id, 'from': from_account, 'to': to_account, 'amount': amount, 'timestamp': datetime.now().isoformat() }) return { 'status': 'Success', 'amount': amount, 'from_account': from_account, 'to_account': to_account, 'timestamp': datetime.now().isoformat() } # Create Open Banking platform platform = OpenBankingPlatform() # Add customers platform.add_customer('CUST001', 'John Smith', 'john@email.com') platform.add_customer('CUST002', 'Jane Doe', 'jane@email.com') # Add accounts platform.add_account('ACC001', 'CUST001', 'Checking', 5000) platform.add_account('ACC002', 'CUST001', 'Savings', 10000) platform.add_account('ACC003', 'CUST002', 'Checking', 3000) # Register third-party apps platform.register_third_party('APP001', 'FinApp', 'Personal Finance Management') platform.register_third_party('APP002', 'PayTech', 'Payment Processing') # Grant consent platform.grant_consent('CUST001', 'APP001', ['view_accounts', 'view_transactions']) platform.grant_consent('CUST001', 'APP002', ['view_accounts', 'initiate_payments']) print("Open Banking Platform Initialised:") print(f"Customers: {len(platform.customers)}") print(f"Accounts: {len(platform.accounts)}") print(f"Third-Party Apps: {len(platform.third_party_apps)}") print(f"Consents Granted: {len(platform.consents)}") # Simulate API calls print("\nSimulating API Calls:") # Get accounts (APP001) result = platform.get_accounts('CUST001', 'APP001') print(f"APP001 -> Get Accounts: {json.dumps(result, indent=2)}") # Initiate payment (APP002) result = platform.initiate_payment('CUST001', 'APP002', 'ACC001', 'ACC003', 1000) print(f"APP002 -> Initiate Payment: {json.dumps(result, indent=2)}") # Get accounts after payment result = platform.get_accounts('CUST001', 'APP001') print(f"\nAccounts after payment: {json.dumps(result, indent=2)}") # Check API call logs print(f"\nTotal API Calls: {len(platform.api_calls)}") # ---------------------------------------------------------------- # PART C: API METRICS DASHBOARD # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART C: API Metrics Dashboard") print("-"*60) api_metrics = pd.DataFrame({ 'Metric': [ 'API Calls (Daily)', 'API Availability', 'Average Response Time', 'Error Rate', 'API Success Rate', 'Active Third-Party Apps', 'Consented Customers', 'API Revenue' ], 'Current Value': [ '250,000', '99.8%', '145 ms', '0.8%', '99.2%', '45', '12,500', '$1.2M/year' ], 'Target Value': [ '500,000', '> 99.9%', '< 100 ms', '< 0.3%', '> 99.7%', '100+', '25,000+', '$3M/year' ], 'Status': ['🟡', '🟡', '🟡', '🟡', '🟡', '🟡', '🟡', '🟡'] }) print("API Metrics Dashboard:") print(api_metrics.to_string(index=False)) # ---------------------------------------------------------------- # PART D: API USAGE ANALYSIS # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART D: API Usage Analysis") print("-"*60) # Simulate API usage data np.random.seed(42) n_calls = 1000 api_usage = pd.DataFrame({ 'timestamp': [datetime.now() - timedelta(minutes=np.random.randint(0, 1440)) for _ in range(n_calls)], 'api_name': np.random.choice(['Accounts API', 'Payments API', 'Transactions API', 'Cards API', 'Customers API', 'Products API'], n_calls), 'app_id': np.random.choice(['APP001', 'APP002', 'APP003', 'APP004', 'APP005'], n_calls), 'response_time_ms': np.random.gamma(2, 20, n_calls).clip(20, 200).astype(int), 'status': np.random.choice(['Success', 'Success', 'Success', 'Error'], n_calls, p=[0.97, 0.01, 0.01, 0.01]), 'customer_id': np.random.choice(['CUST001', 'CUST002', 'CUST003', 'CUST004', 'CUST005'], n_calls) }) print("API Usage Data Sample:") print(api_usage.head()) # Summary by API api_summary = api_usage.groupby('api_name').agg({ 'response_time_ms': 'mean', 'status': lambda x: (x == 'Success').mean() * 100 }).round(2) api_summary.columns = ['Avg Response Time (ms)', 'Success Rate (%)'] print("\nAPI Usage Summary:") print(api_summary) # Visualise fig, axes = plt.subplots(2, 2, figsize=(14, 10)) # API Call Volume ax = axes[0, 0] api_counts = api_usage['api_name'].value_counts() ax.bar(api_counts.index, api_counts.values, color='teal', alpha=0.7) ax.set_xlabel('API') ax.set_ylabel('Call Volume') ax.set_title('API Call Volume') ax.tick_params(axis='x', rotation=45) # Response Time ax = axes[0, 1] api_usage.boxplot(column='response_time_ms', by='api_name', ax=ax) ax.set_title('Response Time by API') ax.set_ylabel('Response Time (ms)') ax.set_xlabel('') # Success Rate by API ax = axes[1, 0] success_rates = api_usage.groupby('api_name').apply(lambda x: (x['status'] == 'Success').mean() * 100) ax.bar(success_rates.index, success_rates.values, color='green', alpha=0.7) ax.axhline(y=99, color='red', linestyle='--', label='Target (99%)') ax.set_xlabel('API') ax.set_ylabel('Success Rate (%)') ax.set_title('API Success Rate') ax.legend() ax.tick_params(axis='x', rotation=45) # Usage by App ax = axes[1, 1] app_counts = api_usage['app_id'].value_counts() ax.pie(app_counts.values, labels=app_counts.index, autopct='%1.1f%%') ax.set_title('API Usage by Third-Party App') plt.tight_layout() plt.savefig('api_usage.png', dpi=300, bbox_inches='tight') plt.show() print("API usage visualisation saved as 'api_usage.png'") # ---------------------------------------------------------------- # PART E: API SECURITY FRAMEWORK # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART E: API Security Framework") print("-"*60) security_controls = { "Authentication": { "Description": "Verify the identity of the API caller.", "Controls": [ "OAuth 2.0 / OpenID Connect", "API Keys (for internal APIs)", "Client Certificates (mTLS)", "Biometric Authentication (mobile)" ] }, "Authorisation": { "Description": "Control what the API caller can access.", "Controls": [ "Role-Based Access Control (RBAC)", "Permission Scopes (OAuth scopes)", "Consent Management", "Attribute-Based Access Control (ABAC)" ] }, "Data Protection": { "Description": "Protect data in transit and at rest.", "Controls": [ "TLS 1.3 for all API calls", "Encryption at rest (AES-256)", "Data Masking for sensitive fields", "Tokenisation of card data" ] }, "Threat Protection": { "Description": "Detect and prevent attacks.", "Controls": [ "Rate Limiting (DoS protection)", "Web Application Firewall (WAF)", "API Gateway with security policies", "Real-time threat monitoring" ] }, "Governance": { "Description": "Manage API lifecycle and compliance.", "Controls": [ "API Lifecycle Management", "Version Control and Deprecation", "Compliance Reviews (GDPR, PCI DSS)", "Regular Security Audits" ] } } print("API Security Framework:") for domain, details in security_controls.items(): print(f"\n{domain}:") print(f" {details['Description']}") print(" Controls:") for control in details['Controls']: print(f" • {control}") # ---------------------------------------------------------------- # PART F: OPEN BANKING BUSINESS MODELS # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART F: Open Banking Business Models") print("-"*60) business_models = pd.DataFrame({ 'Model': [ 'Data Aggregation', 'Payment Initiation', 'Lending', 'Financial Management', 'Identity Verification', 'Fraud Detection', 'Wealth Management' ], 'Revenue Model': [ 'Subscription, Data Licensing', 'Transaction Fees', 'Interest, Origination Fees', 'Subscription, Advisory Fees', 'Per-Verification Fee', 'Transaction Fee', 'AUM Fees' ], 'Partners': [ 'AISPs, Aggregators', 'PISPs, Merchants', 'Fintech Lenders', 'PFM Apps', 'Identity Providers', 'Fintech, Banks', 'Robo-Advisors' ], 'Bank Role': [ 'Data Provider', 'Payment Processor', 'Funding Partner', 'Data Provider', 'Verification Provider', 'Data Provider', 'Custodian' ] }) print("Open Banking Business Models:") print(business_models.to_string(index=False)) # ---------------------------------------------------------------- # PART G: API STRATEGY RECOMMENDATIONS # ---------------------------------------------------------------- print("\n" + "-"*60) print("PART G: API Strategy Recommendations") print("-"*60) strategy = { "1. API Governance": { "Actions": [ "Establish API governance framework.", "Define API standards and guidelines.", "Implement API lifecycle management.", "Create API product owner roles." ], "Priority": "High", "Timeline": "0-6 months" }, "2. API Design": { "Actions": [ "Adopt OpenAPI/Swagger for documentation.", "Design consistent, RESTful APIs.", "Implement versioning strategy.", "Build developer portal and sandbox." ], "Priority": "High", "Timeline": "0-6 months" }, "3. Security": { "Actions": [ "Implement OAuth 2.0 / OIDC.", "Enable mTLS for partner APIs.", "Implement rate limiting and throttling.", "Establish API security monitoring." ], "Priority": "Critical", "Timeline": "0-3 months" }, "4. Partner Ecosystem": { "Actions": [ "Identify strategic partners.", "Build partner onboarding process.", "Develop partner incentives.", "Create an API marketplace." ], "Priority": "High", "Timeline": "6-12 months" }, "5. Analytics": { "Actions": [ "Implement API analytics and monitoring.", "Track API performance and usage.", "Build API monetisation capabilities.", "Enable self-service analytics." ], "Priority": "Medium", "Timeline": "6-12 months" } } for item, details in strategy.items(): print(f"\n{item}:") for action in details['Actions']: print(f" • {action}") print(f" Priority: {details['Priority']}") print(f" Timeline: {details['Timeline']}") # ---------------------------------------------------------------- # PART H: SUMMARY AND RECOMMENDATIONS # ---------------------------------------------------------------- print("\n" + "="*70) print("PART H: Summary and Recommendations") print("="*70) print(""" API Banking and Open Banking Platforms – Key Takeaways: 1. API banking enables secure, standardised access to banking services. 2. Open Banking is a regulatory framework for sharing customer data with TPPs. 3. Key APIs: accounts, payments, transactions, cards, customers, products. 4. API security: authentication, authorisation, encryption, threat protection. 5. Open Banking business models: data aggregation, payment initiation, lending, PFM. 6. Key metrics: API calls, availability, response time, success rate. 7. Strategy: governance, design, security, ecosystem, analytics. Recommendations: - Build an API-first banking platform. - Implement Open Banking APIs (PSD2, etc.). - Establish API governance and security. - Create a developer portal and partner ecosystem. - Measure and optimise API performance. - Explore API monetisation opportunities. """) print("="*70) print("END OF LESSON 8 – MODULE 3") print("="*70)
SECTION 8: SUMMARY FOR THE DATA PRACTITIONER
-
API banking enables secure, standardised access to banking services and data.
-
Open Banking is a regulatory framework that requires banks to share customer data with authorised third-party providers.
-
Key APIs include accounts, payments, transactions, cards, customers, and products.
-
API security requires authentication (OAuth 2.0), authorisation (scopes, RBAC), encryption (TLS), and threat protection.
-
Open Banking business models include data aggregation, payment initiation, lending, financial management, identity verification, and fraud detection.
-
Key metrics include API call volume, availability, response time, success rate, and error rate.
-
API strategy should focus on governance, design, security, partner ecosystem, and analytics.
SECTION 9: RECOMMENDED NEXT STEPS
-
Build an API-first banking platform.
-
Implement Open Banking APIs (PSD2, etc.).
-
Establish API governance and security.
-
Create a developer portal and partner ecosystem.
-
Measure and optimise API performance.
-
Explore API monetisation opportunities.
[END OF LESSON 8 – MODULE 3]
[END OF MODULE 3]