Morten Sæther

← Blog

Custom API Development for Power Pages

#22 · 19 July 2026

REST, GraphQL, OAuth, and integrations that don't fall over when the other end does

No portal lives alone. There’s always a CRM, a legacy database, some SaaS platform that owns half the data you need to display.

This post is about connecting to them - authentication that holds up, data transformation you can follow, and failure handling for the inevitable morning when the other system is down and yours shouldn’t be.

You’ll want the previous post under your belt first, plus an understanding of HTTP, JSON and the usual authentication mechanisms.

Step by step

1. Pick your integration point

Power Pages gives you three places to call an API from, and the choice matters.

Client-side, in JavaScript, when the token belongs to the signed-in user:

// Modern fetch API with error handling
class PowerPagesAPIClient {
    constructor(baseURL, accessToken) {
        this.baseURL = baseURL;
        this.accessToken = accessToken;
        this.defaultHeaders = {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${accessToken}`
        };
    }

    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            ...options,
            headers: { ...this.defaultHeaders, ...options.headers }
        };

        try {
            const response = await fetch(url, config);

            if (!response.ok) {
                throw new APIError(
                    `HTTP ${response.status}: ${response.statusText}`,
                    response.status
                );
            }

            return await response.json();
        } catch (error) {
            this.handleError(error);
            throw error;
        }
    }

    async get(endpoint, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const url = queryString ? `${endpoint}?${queryString}` : endpoint;
        return this.request(url, { method: 'GET' });
    }

    async post(endpoint, data) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    async put(endpoint, data) {
        return this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    async delete(endpoint) {
        return this.request(endpoint, { method: 'DELETE' });
    }

    handleError(error) {
        console.error('API Error:', error);
        // Log to Power Pages or external monitoring system
        this.logError(error);
    }

    logError(error) {
        // Implementation depends on your logging strategy
        if (window.applicationInsights) {
            window.applicationInsights.trackException({ exception: error });
        }
    }
}

// Custom error class for API operations
class APIError extends Error {
    constructor(message, status) {
        super(message);
        this.name = 'APIError';
        this.status = status;
    }
}

Server-side, in server logic: JavaScript (ECMAScript 2023, no DOM and no fetch) that runs on the Power Pages server, hidden from the browser and gated by web roles and table permissions. It can call external REST APIs with keys that never leave the server, and the page reaches it at /_api/serverlogics/<name> with the request verification token in the call. Tenant admins can block its outbound calls per site, so check that before you build on it.

Server-side, through a Power Automate cloud flow. The flow needs the “When Power Pages calls a flow” trigger, has to be solution-aware, is added to the site under Set up > Cloud flows with the web roles that may call it, and needs a Power Automate license. The site then calls it like this:

// Call a cloud flow registered on the site
async function callFlow(flowId, payload) {
    const token = await new Promise((resolve, reject) =>
        shell.getTokenDeferred().done(resolve).fail(reject));

    const response = await fetch(`/_api/cloudflow/v1.0/trigger/${flowId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            '__RequestVerificationToken': token
        },
        body: JSON.stringify(payload) // Property names must match the trigger's input parameters
    });

    if (!response.ok) {
        throw new APIError(`Flow call failed: HTTP ${response.status}`, response.status);
    }

    // 202 Accepted when the flow has no Response action
    return response.status === 202 ? null : response.json();
}

Rule of thumb: anything involving a credential the user shouldn’t see goes server-side. No exceptions, no “it’s only a read key”.

2. Authentication

OAuth 2.0 authorization code flow with PKCE, which Entra requires for browser apps. For Entra I use MSAL rather than this; the class shows what a library does for you:

// OAuth 2.0 authorization code flow with PKCE (public client, no secret)
class OAuthManager {
    constructor({ clientId, redirectUri, authUrl, tokenUrl }) {
        this.clientId = clientId;
        this.redirectUri = redirectUri;
        this.authUrl = authUrl;
        this.tokenUrl = tokenUrl;
        this.tokens = JSON.parse(sessionStorage.getItem('oauth_tokens') || 'null');
    }

    // Initiate OAuth flow
    async authorize(scopes = []) {
        const state = this.randomString(16);
        const verifier = this.randomString(64);
        sessionStorage.setItem('oauth_state', state);
        sessionStorage.setItem('oauth_verifier', verifier);

        const params = new URLSearchParams({
            response_type: 'code',
            client_id: this.clientId,
            redirect_uri: this.redirectUri,
            scope: scopes.join(' '),
            state,
            code_challenge: await this.challenge(verifier),
            code_challenge_method: 'S256'
        });

        window.location.href = `${this.authUrl}?${params}`;
    }

    // Handle OAuth callback
    async handleCallback() {
        const urlParams = new URLSearchParams(window.location.search);

        const error = urlParams.get('error');
        if (error) {
            throw new Error(`Authorization failed: ${error}`);
        }

        const state = urlParams.get('state');
        const storedState = sessionStorage.getItem('oauth_state');
        sessionStorage.removeItem('oauth_state');
        if (!state || state !== storedState) {
            throw new Error('Invalid OAuth state parameter');
        }

        const code = urlParams.get('code');
        if (!code) {
            throw new Error('No authorization code in callback');
        }

        const verifier = sessionStorage.getItem('oauth_verifier');
        sessionStorage.removeItem('oauth_verifier');

        await this.requestTokens({
            grant_type: 'authorization_code',
            code,
            redirect_uri: this.redirectUri,
            code_verifier: verifier
        });
    }

    // Refresh access token
    async refreshAccessToken() {
        if (!this.tokens?.refreshToken) {
            throw new Error('No refresh token available');
        }

        await this.requestTokens({
            grant_type: 'refresh_token',
            refresh_token: this.tokens.refreshToken
        });
    }

    async requestTokens(params) {
        const response = await fetch(this.tokenUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({ client_id: this.clientId, ...params })
        });

        const data = await response.json();
        if (!response.ok) {
            throw new Error(`Token request failed: ${data.error || response.status}`);
        }

        this.tokens = {
            accessToken: data.access_token,
            // A new refresh token replaces the old one when the server issues one
            refreshToken: data.refresh_token || this.tokens?.refreshToken,
            expiresAt: Date.now() + data.expires_in * 1000
        };
        sessionStorage.setItem('oauth_tokens', JSON.stringify(this.tokens));
    }

    async getAccessToken() {
        if (!this.tokens) {
            throw new Error('Not authenticated');
        }
        if (Date.now() >= this.tokens.expiresAt - 60000) {
            await this.refreshAccessToken();
        }
        return this.tokens.accessToken;
    }

    isAuthenticated() {
        return !!this.tokens;
    }

    async getAuthHeaders() {
        return {
            'Authorization': `Bearer ${await this.getAccessToken()}`
        };
    }

    randomString(length) {
        return this.base64url(crypto.getRandomValues(new Uint8Array(length)));
    }

    async challenge(verifier) {
        const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
        return this.base64url(new Uint8Array(digest));
    }

    base64url(bytes) {
        return btoa(String.fromCharCode(...bytes))
            .replace(/\+/g, '-')
            .replace(/\//g, '_')
            .replace(/=+$/, '');
    }
}

3. GraphQL, where it fits

// GraphQL client for Power Pages
class GraphQLClient {
    constructor(endpoint, authManager) {
        this.endpoint = endpoint;
        this.authManager = authManager;
    }

    async query(query, variables = {}) {
        return this.request({ query, variables });
    }

    async mutation(mutation, variables = {}) {
        return this.request({ query: mutation, variables });
    }

    async request(payload, retried = false) {
        const headers = {
            'Content-Type': 'application/json',
            ...(await this.authManager.getAuthHeaders())
        };

        const response = await fetch(this.endpoint, {
            method: 'POST',
            headers,
            body: JSON.stringify(payload)
        });

        if (response.status === 401 && !retried) {
            await this.authManager.refreshAccessToken();
            return this.request(payload, true); // Retry once
        }

        if (!response.ok) {
            throw new APIError(`GraphQL request failed: HTTP ${response.status}`, response.status);
        }

        const result = await response.json();

        if (result.errors) {
            throw new GraphQLError(result.errors);
        }

        return result.data;
    }
}

class GraphQLError extends Error {
    constructor(errors) {
        super(errors.map(e => e.message).join('; '));
        this.name = 'GraphQLError';
        this.errors = errors;
    }
}

// Example GraphQL queries and mutations
const USER_QUERIES = {
    GET_USER_PROFILE: `
        query GetUserProfile($userId: ID!) {
            user(id: $userId) {
                id
                name
                email
                profile {
                    avatar
                    department
                    lastLogin
                }
                permissions {
                    canEdit
                    canDelete
                    canApprove
                }
            }
        }
    `,
    
    UPDATE_USER_PROFILE: `
        mutation UpdateUserProfile($userId: ID!, $input: UserUpdateInput!) {
            updateUser(id: $userId, input: $input) {
                id
                name
                email
                updatedAt
            }
        }
    `,
    
    SEARCH_USERS: `
        query SearchUsers($searchTerm: String!, $filters: UserFilters) {
            searchUsers(term: $searchTerm, filters: $filters) {
                totalCount
                pageInfo {
                    hasNextPage
                    hasPreviousPage
                    startCursor
                    endCursor
                }
                edges {
                    node {
                        id
                        name
                        email
                        department
                    }
                }
            }
        }
    `
};

// Usage example in Power Pages
class UserManager {
    constructor(graphqlClient) {
        this.client = graphqlClient;
    }

    async getUserProfile(userId) {
        return this.client.query(USER_QUERIES.GET_USER_PROFILE, { userId });
    }

    async updateUserProfile(userId, updates) {
        return this.client.mutation(USER_QUERIES.UPDATE_USER_PROFILE, {
            userId,
            input: updates
        });
    }

    async searchUsers(searchTerm, filters = {}) {
        return this.client.query(USER_QUERIES.SEARCH_USERS, {
            searchTerm,
            filters
        });
    }
}

4. Transform the data

// Data transformation engine for API responses
class DataTransformer {
    constructor() {
        this.transformations = new Map();
    }

    // Register transformation schemas
    registerTransformation(name, schema) {
        this.transformations.set(name, schema);
    }

    // Transform data using registered schema
    transform(data, schemaName, context = {}) {
        const schema = this.transformations.get(schemaName);
        if (!schema) {
            throw new Error(`Transformation schema '${schemaName}' not found`);
        }

        if (Array.isArray(data)) {
            return data.map(item => this.transformObject(item, schema, context));
        }

        return this.transformObject(data, schema, context);
    }

    transformObject(obj, schema, context) {
        const result = {};

        for (const [targetKey, mapping] of Object.entries(schema)) {
            if (typeof mapping === 'string') {
                // Simple field mapping
                result[targetKey] = this.getNestedValue(obj, mapping);
            } else if (typeof mapping === 'function') {
                // Function transformation
                result[targetKey] = mapping(obj, context);
            } else if (mapping.type === 'computed') {
                // Computed field
                result[targetKey] = this.computeValue(obj, mapping, context);
            } else if (mapping.type === 'nested') {
                // Nested transformation
                const nestedData = this.getNestedValue(obj, mapping.source);
                result[targetKey] = this.transform(nestedData, mapping.schema, context);
            }
        }

        return result;
    }

    getNestedValue(obj, path) {
        return path.split('.').reduce((current, key) => current?.[key], obj);
    }

    computeValue(obj, mapping, context) {
        const dependencies = mapping.dependencies || [];
        const values = dependencies.map(dep => this.getNestedValue(obj, dep));
        return mapping.compute(...values, context);
    }
}

// Example transformation schemas
const TRANSFORMATION_SCHEMAS = {
    // Transform external API user to Power Pages contact
    EXTERNAL_USER_TO_CONTACT: {
        contactId: 'id',
        fullName: (obj) => `${obj.firstName} ${obj.lastName}`,
        emailAddress: 'email',
        phoneNumber: 'phone',
        department: 'attributes.department',
        isActive: (obj) => obj.status === 'active',
        lastLoginDate: {
            type: 'computed',
            dependencies: ['lastLogin'],
            compute: (lastLogin) => lastLogin ? new Date(lastLogin).toISOString() : null
        },
        address: {
            type: 'nested',
            source: 'address',
            schema: 'ADDRESS_MAPPING'
        }
    },

    ADDRESS_MAPPING: {
        street: 'street1',
        city: 'city',
        state: 'state',
        postalCode: 'zipCode',
        country: 'country'
    },

    // Transform Power Pages form data to external API format
    CONTACT_FORM_TO_EXTERNAL: {
        firstName: 'firstname',
        lastName: 'lastname',
        email: 'emailaddress1',
        phone: 'telephone1',
        company: 'parentcustomerid.name',
        jobTitle: 'jobtitle',
        customFields: (obj) => {
            const customFields = {};
            for (const [key, value] of Object.entries(obj)) {
                if (key.startsWith('custom_')) {
                    customFields[key.replace('custom_', '')] = value;
                }
            }
            return customFields;
        }
    }
};

// Initialize transformer with schemas
const transformer = new DataTransformer();
Object.entries(TRANSFORMATION_SCHEMAS).forEach(([name, schema]) => {
    transformer.registerTransformation(name, schema);
});

Every integration ends up with a mapping layer. Better to make it explicit and testable than to scatter field renames through your UI code.

5. Cache aggressively

// Multi-level caching system for API responses
class APICache {
    constructor(options = {}) {
        this.memoryCache = new Map();
        this.sessionCache = window.sessionStorage;
        this.localCache = window.localStorage;
        this.defaultTTL = options.defaultTTL || 300000; // 5 minutes
        this.maxMemorySize = options.maxMemorySize || 100;
    }

    // Generate cache key from request parameters
    generateKey(url, params = {}) {
        const paramString = JSON.stringify(params, Object.keys(params).sort());
        return `api_cache_${btoa(url + paramString)}`;
    }

    // Store data in appropriate cache level
    set(key, data, ttl = this.defaultTTL, level = 'memory') {
        const cacheItem = {
            data,
            timestamp: Date.now(),
            ttl,
            level
        };

        switch (level) {
            case 'memory':
                this.setMemoryCache(key, cacheItem);
                break;
            case 'session':
                this.sessionCache.setItem(key, JSON.stringify(cacheItem));
                break;
            case 'local':
                this.localCache.setItem(key, JSON.stringify(cacheItem));
                break;
        }
    }

    setMemoryCache(key, item) {
        if (this.memoryCache.size >= this.maxMemorySize) {
            // Remove oldest item
            const firstKey = this.memoryCache.keys().next().value;
            this.memoryCache.delete(firstKey);
        }
        this.memoryCache.set(key, item);
    }

    // Retrieve data from cache
    get(key) {
        // Check memory cache first
        let item = this.memoryCache.get(key);
        if (item && this.isValid(item)) {
            return item.data;
        }

        // Check session cache
        const sessionItem = this.sessionCache.getItem(key);
        if (sessionItem) {
            item = JSON.parse(sessionItem);
            if (this.isValid(item)) {
                // Promote to memory cache
                this.memoryCache.set(key, item);
                return item.data;
            }
            this.sessionCache.removeItem(key);
        }

        // Check local cache
        const localItem = this.localCache.getItem(key);
        if (localItem) {
            item = JSON.parse(localItem);
            if (this.isValid(item)) {
                // Promote to session cache
                this.sessionCache.setItem(key, JSON.stringify(item));
                return item.data;
            }
            this.localCache.removeItem(key);
        }

        return null;
    }

    isValid(item) {
        return Date.now() - item.timestamp < item.ttl;
    }

    // Clear expired items
    cleanup() {
        // Memory cache cleanup
        for (const [key, item] of this.memoryCache.entries()) {
            if (!this.isValid(item)) {
                this.memoryCache.delete(key);
            }
        }

        // Session cache cleanup
        this.cleanupStorage(this.sessionCache);
        
        // Local cache cleanup
        this.cleanupStorage(this.localCache);
    }

    cleanupStorage(storage) {
        const keysToRemove = [];
        for (let i = 0; i < storage.length; i++) {
            const key = storage.key(i);
            if (key?.startsWith('api_cache_')) {
                try {
                    const item = JSON.parse(storage.getItem(key));
                    if (!this.isValid(item)) {
                        keysToRemove.push(key);
                    }
                } catch (e) {
                    keysToRemove.push(key);
                }
            }
        }
        keysToRemove.forEach(key => storage.removeItem(key));
    }

    // Cache-aware request wrapper; fetcher does the actual call
    async cachedRequest(method, endpoint, params, fetcher, options = {}) {
        const cacheKey = this.generateKey(`${method}:${endpoint}`, params);

        // Try to get from cache first
        const cachedData = this.get(cacheKey);
        if (cachedData) {
            return cachedData;
        }

        // Make API request
        const data = await fetcher();
        
        // Cache the response
        const ttl = options.ttl || this.defaultTTL;
        const level = options.cacheLevel || 'memory';
        this.set(cacheKey, data, ttl, level);

        return data;
    }
}

// Usage with API client
class CachedAPIClient extends PowerPagesAPIClient {
    constructor(baseURL, accessToken, cacheOptions = {}) {
        super(baseURL, accessToken);
        this.cache = new APICache(cacheOptions);
        
        // Clean up cache periodically
        setInterval(() => this.cache.cleanup(), 60000); // Every minute
    }

    async get(endpoint, params = {}, cacheOptions = {}) {
        if (cacheOptions.useCache !== false) {
            // super.get, not this.get, or the wrapper calls itself forever
            return this.cache.cachedRequest('get', endpoint, params,
                () => super.get(endpoint, params), cacheOptions);
        }
        return super.get(endpoint, params);
    }
}

6. Plan for the other end failing

Circuit breakers, because retrying against a dead service just makes you slow too:

// Circuit breaker implementation for external API calls
class CircuitBreaker {
    constructor(options = {}) {
        this.failureThreshold = options.failureThreshold || 5;
        this.resetTimeout = options.resetTimeout || 60000;
        this.state = 'CLOSED'; // CLOSED, OPEN, HALF_OPEN
        this.failureCount = 0;
        this.lastFailureTime = null;
        this.successCount = 0;
    }

    async execute(apiCall) {
        if (this.state === 'OPEN') {
            if (Date.now() - this.lastFailureTime > this.resetTimeout) {
                this.state = 'HALF_OPEN';
                this.successCount = 0;
            } else {
                throw new Error('Circuit breaker is OPEN');
            }
        }

        try {
            const result = await apiCall();
            this.onSuccess();
            return result;
        } catch (error) {
            this.onFailure();
            throw error;
        }
    }

    onSuccess() {
        this.failureCount = 0;
        if (this.state === 'HALF_OPEN') {
            this.successCount++;
            if (this.successCount >= 3) {
                this.state = 'CLOSED';
            }
        }
    }

    onFailure() {
        this.failureCount++;
        this.lastFailureTime = Date.now();
        // Any failure while half-open means the fault is still there
        if (this.state === 'HALF_OPEN' || this.failureCount >= this.failureThreshold) {
            this.state = 'OPEN';
        }
    }

    getState() {
        return {
            state: this.state,
            failureCount: this.failureCount,
            lastFailureTime: this.lastFailureTime
        };
    }
}

// Retry pattern with exponential backoff
class RetryHandler {
    constructor(options = {}) {
        this.maxRetries = options.maxRetries || 3;
        this.baseDelay = options.baseDelay || 1000;
        this.maxDelay = options.maxDelay || 10000;
        this.backoffFactor = options.backoffFactor || 2;
    }

    async execute(apiCall, retryCondition = this.defaultRetryCondition) {
        let lastError;
        
        for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
            try {
                return await apiCall();
            } catch (error) {
                lastError = error;
                
                if (attempt === this.maxRetries || !retryCondition(error, attempt)) {
                    throw error;
                }

                const delay = this.calculateDelay(attempt);
                await this.sleep(delay);
            }
        }
        
        throw lastError;
    }

    calculateDelay(attempt) {
        const delay = this.baseDelay * Math.pow(this.backoffFactor, attempt);
        return Math.min(delay, this.maxDelay);
    }

    defaultRetryCondition(error, attempt) {
        // Retry on network errors or 5xx server errors
        return error.status >= 500 || error.name === 'NetworkError';
    }

    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// Resilient API client combining circuit breaker and retry
class ResilientAPIClient extends CachedAPIClient {
    constructor(baseURL, accessToken, options = {}) {
        super(baseURL, accessToken, options.cacheOptions);
        this.circuitBreaker = new CircuitBreaker(options.circuitBreakerOptions);
        this.retryHandler = new RetryHandler(options.retryOptions);
    }

    async request(endpoint, options = {}) {
        const apiCall = () => super.request(endpoint, options);
        
        if (options.useCircuitBreaker !== false) {
            return this.circuitBreaker.execute(() => 
                this.retryHandler.execute(apiCall)
            );
        }
        
        return this.retryHandler.execute(apiCall);
    }
}

And rate limiting, because most APIs will cut you off eventually:

// Token bucket rate limiter
class TokenBucket {
    constructor(capacity, refillRate, refillPeriod = 1000) {
        this.capacity = capacity;
        this.tokens = capacity;
        this.refillRate = refillRate;
        this.refillPeriod = refillPeriod;
        this.lastRefill = Date.now();
    }

    consume(tokens = 1) {
        this.refill();
        
        if (this.tokens >= tokens) {
            this.tokens -= tokens;
            return true;
        }
        
        return false;
    }

    refill() {
        const now = Date.now();
        const timePassed = now - this.lastRefill;
        // Fractional tokens: rounding down here would never refill under frequent polling
        const tokensToAdd = (timePassed / this.refillPeriod) * this.refillRate;

        this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
        this.lastRefill = now;
    }

    getStatus() {
        this.refill();
        return {
            tokens: Math.floor(this.tokens),
            capacity: this.capacity,
            percentage: (this.tokens / this.capacity) * 100
        };
    }
}

// Rate-limited API client
class RateLimitedAPIClient extends ResilientAPIClient {
    constructor(baseURL, accessToken, options = {}) {
        super(baseURL, accessToken, options);
        this.rateLimiter = new TokenBucket(
            options.rateLimit?.capacity || 100,
            options.rateLimit?.refillRate || 10,
            options.rateLimit?.refillPeriod || 1000
        );
        this.rateLimitQueue = [];
        this.isProcessingQueue = false;
    }

    async request(endpoint, options = {}) {
        return new Promise((resolve, reject) => {
            this.rateLimitQueue.push({
                endpoint,
                options,
                resolve,
                reject,
                timestamp: Date.now()
            });

            this.processQueue();
        });
    }

    async processQueue() {
        if (this.isProcessingQueue || this.rateLimitQueue.length === 0) {
            return;
        }

        this.isProcessingQueue = true;

        while (this.rateLimitQueue.length > 0) {
            if (!this.rateLimiter.consume()) {
                // Wait for tokens to be available
                await this.sleep(100);
                continue;
            }

            const request = this.rateLimitQueue.shift();
            
            try {
                const result = await super.request(request.endpoint, request.options);
                request.resolve(result);
            } catch (error) {
                request.reject(error);
            }
        }

        this.isProcessingQueue = false;
    }

    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    getRateLimitStatus() {
        return this.rateLimiter.getStatus();
    }
}

Two real integrations

Salesforce, with the signed-in user’s own OAuth access token:

// Salesforce API integration for Power Pages
class SalesforceIntegration {
    constructor(instanceUrl, accessToken) {
        this.apiClient = new RateLimitedAPIClient(
            `${instanceUrl}/services/data/v58.0`,
            accessToken,
            {
                rateLimit: { capacity: 100, refillRate: 20 },
                circuitBreakerOptions: { failureThreshold: 3 }
            }
        );
    }

    // Get account information
    async getAccount(accountId) {
        const endpoint = `/sobjects/Account/${accountId}`;
        return this.apiClient.get(endpoint, {}, {
            useCache: true,
            ttl: 300000, // 5 minutes
            cacheLevel: 'session'
        });
    }

    // Search for contacts
    async searchContacts(searchTerm, filters = {}) {
        const soql = this.buildContactSearchQuery(searchTerm, filters);
        const endpoint = `/query/?q=${encodeURIComponent(soql)}`;
        return this.apiClient.get(endpoint);
    }

    buildContactSearchQuery(searchTerm, filters) {
        const term = this.escapeSoql(searchTerm);
        let query = `SELECT Id, FirstName, LastName, Email, Phone, AccountId
                     FROM Contact
                     WHERE (Name LIKE '%${term}%' OR Email LIKE '%${term}%')`;

        if (filters.accountId) {
            query += ` AND AccountId = '${this.escapeSoql(filters.accountId)}'`;
        }

        query += ` ORDER BY LastModifiedDate DESC LIMIT 50`;
        return query;
    }

    // Quotes and backslashes in user input would otherwise change the query
    escapeSoql(value) {
        return String(value).replace(/['\\]/g, '\\$&');
    }

    async createContact(contactData) {
        const endpoint = '/sobjects/Contact/';
        return this.apiClient.post(endpoint, this.transformToSalesforceFormat(contactData));
    }

    transformToSalesforceFormat(powerPagesData) {
        return {
            FirstName: powerPagesData.firstname,
            LastName: powerPagesData.lastname,
            Email: powerPagesData.emailaddress1,
            Phone: powerPagesData.telephone1,
            Title: powerPagesData.jobtitle,
            Description: powerPagesData.description
        };
    }
}

Shopify is different. The Admin API token is a shop-level secret, so by my own rule it never goes into page script. The flow holds the token and makes the Admin API call; the page calls the flow:

// Shopify order lookup through a cloud flow that holds the Admin API token
class ShopifyIntegration {
    constructor(flowIds) {
        this.flowIds = flowIds; // { customerOrders, orderDetails }
        this.cache = new APICache({ defaultTTL: 60000 }); // 1 minute for order data
    }

    // Get customer orders
    async getCustomerOrders(customerId, limit = 50) {
        const response = await this.cache.cachedRequest(
            'flow', this.flowIds.customerOrders, { customerId, limit },
            () => callFlow(this.flowIds.customerOrders, { customerId, limit }),
            { ttl: 300000, cacheLevel: 'session' }
        );

        return response.orders.map(order => this.transformOrder(order));
    }

    // Get order details
    async getOrderDetails(orderId) {
        const response = await this.cache.cachedRequest(
            'flow', this.flowIds.orderDetails, { orderId },
            () => callFlow(this.flowIds.orderDetails, { orderId })
        );

        return this.transformOrderDetails(response.order);
    }

    transformOrder(shopifyOrder) {
        return {
            orderId: shopifyOrder.id,
            orderNumber: shopifyOrder.order_number,
            orderDate: shopifyOrder.created_at,
            totalAmount: parseFloat(shopifyOrder.total_price),
            status: this.mapOrderStatus(shopifyOrder.financial_status, shopifyOrder.fulfillment_status),
            itemCount: shopifyOrder.line_items?.length || 0,
            trackingAvailable: shopifyOrder.fulfillment_status === 'fulfilled'
        };
    }

    transformOrderDetails(shopifyOrder) {
        return {
            ...this.transformOrder(shopifyOrder),
            items: shopifyOrder.line_items.map(item => ({
                productId: item.product_id,
                variantId: item.variant_id,
                name: item.name,
                quantity: item.quantity,
                price: parseFloat(item.price),
                sku: item.sku
            })),
            shippingAddress: shopifyOrder.shipping_address,
            billingAddress: shopifyOrder.billing_address,
            fulfillments: shopifyOrder.fulfillments?.map(f => ({
                trackingNumber: f.tracking_number,
                trackingUrl: f.tracking_url,
                status: f.status
            })) || []
        };
    }

    mapOrderStatus(financialStatus, fulfillmentStatus) {
        if (financialStatus === 'pending') return 'Payment Pending';
        if (financialStatus === 'paid' && !fulfillmentStatus) return 'Processing';
        if (fulfillmentStatus === 'fulfilled') return 'Shipped';
        if (fulfillmentStatus === 'partial') return 'Partially Shipped';
        return 'Unknown';
    }
}

The flow itself is left out; it is an HTTP action against the Admin API with the token in the flow’s connection, and the rate limit is handled there, where the calls actually happen.

Testing and monitoring

A test suite for the integrations:

// Test utilities for API integrations
class APITestSuite {
    constructor(apiClient) {
        this.apiClient = apiClient;
        this.testResults = [];
    }

    async runAllTests() {
        console.log('Starting API integration tests...');
        
        const tests = [
            { name: 'Authentication', test: () => this.testAuthentication() },
            { name: 'Basic CRUD Operations', test: () => this.testCrudOperations() },
            { name: 'Error Handling', test: () => this.testErrorHandling() },
            { name: 'Rate Limiting', test: () => this.testRateLimiting() },
            { name: 'Data Transformation', test: () => this.testDataTransformation() },
            { name: 'Caching', test: () => this.testCaching() }
        ];

        for (const testCase of tests) {
            try {
                console.log(`Running test: ${testCase.name}`);
                const startTime = Date.now();
                await testCase.test();
                const duration = Date.now() - startTime;
                
                this.testResults.push({
                    name: testCase.name,
                    status: 'PASSED',
                    duration
                });
                console.log(`✅ ${testCase.name} - PASSED (${duration}ms)`);
            } catch (error) {
                this.testResults.push({
                    name: testCase.name,
                    status: 'FAILED',
                    error: error.message
                });
                console.error(`❌ ${testCase.name} - FAILED: ${error.message}`);
            }
        }

        this.printTestSummary();
        return this.testResults;
    }

    async testAuthentication() {
        // A request that only succeeds with a valid token
        await this.apiClient.get('/test/auth');
    }

    async testCrudOperations() {
        // Create
        const createData = { name: 'Test Item', description: 'Test Description' };
        const created = await this.apiClient.post('/test/items', createData);
        
        if (!created.id) {
            throw new Error('Create operation failed - no ID returned');
        }

        // Read
        const retrieved = await this.apiClient.get(`/test/items/${created.id}`);
        if (retrieved.name !== createData.name) {
            throw new Error('Read operation failed - data mismatch');
        }

        // Update
        const updateData = { name: 'Updated Test Item' };
        const updated = await this.apiClient.put(`/test/items/${created.id}`, updateData);
        if (updated.name !== updateData.name) {
            throw new Error('Update operation failed');
        }

        // Delete
        await this.apiClient.delete(`/test/items/${created.id}`);
        
        // Verify deletion
        try {
            await this.apiClient.get(`/test/items/${created.id}`);
            throw new Error('Delete operation failed - item still exists');
        } catch (error) {
            if (error.status !== 404) {
                throw new Error('Delete operation failed - unexpected error');
            }
        }
    }

    async testErrorHandling() {
        // Test 404 error
        try {
            await this.apiClient.get('/test/nonexistent');
            throw new Error('Expected 404 error was not thrown');
        } catch (error) {
            if (error.status !== 404) {
                throw new Error(`Expected 404, got ${error.status}`);
            }
        }

        // Test invalid data error
        try {
            await this.apiClient.post('/test/items', { invalid: 'data' });
            throw new Error('Expected validation error was not thrown');
        } catch (error) {
            if (error.status !== 400) {
                throw new Error(`Expected 400, got ${error.status}`);
            }
        }
    }

    async testRateLimiting() {
        if (!this.apiClient.getRateLimitStatus) {
            console.log('Rate limiting not implemented - skipping test');
            return;
        }

        const initialStatus = this.apiClient.getRateLimitStatus();
        const initialTokens = initialStatus.tokens;

        // Make several requests
        for (let i = 0; i < 5; i++) {
            await this.apiClient.get('/test/rate-limit');
        }

        const finalStatus = this.apiClient.getRateLimitStatus();
        if (finalStatus.tokens >= initialTokens) {
            throw new Error('Rate limiting not working - tokens not consumed');
        }
    }

    async testDataTransformation() {
        const testData = {
            externalId: '123',
            firstName: 'John',
            lastName: 'Doe',
            email: 'john.doe@example.com'
        };

        const transformer = new DataTransformer();
        transformer.registerTransformation('TEST_TRANSFORMATION', {
            fullName: (obj) => `${obj.firstName} ${obj.lastName}`
        });
        const transformed = transformer.transform(testData, 'TEST_TRANSFORMATION');
        
        if (!transformed.fullName || transformed.fullName !== 'John Doe') {
            throw new Error('Data transformation failed');
        }
    }

    async testCaching() {
        if (!this.apiClient.cache) {
            console.log('Caching not implemented - skipping test');
            return;
        }

        // First request (should hit API)
        const startTime1 = Date.now();
        await this.apiClient.get('/test/cache', {}, { useCache: true });
        const duration1 = Date.now() - startTime1;

        // Second request (should hit cache)
        const startTime2 = Date.now();
        await this.apiClient.get('/test/cache', {}, { useCache: true });
        const duration2 = Date.now() - startTime2;

        if (duration2 >= duration1) {
            throw new Error('Caching not working - second request took too long');
        }
    }

    printTestSummary() {
        const passed = this.testResults.filter(r => r.status === 'PASSED').length;
        const failed = this.testResults.filter(r => r.status === 'FAILED').length;
        
        console.log('\n=== Test Summary ===');
        console.log(`Total Tests: ${this.testResults.length}`);
        console.log(`Passed: ${passed}`);
        console.log(`Failed: ${failed}`);
        
        if (failed > 0) {
            console.log('\nFailed Tests:');
            this.testResults
                .filter(r => r.status === 'FAILED')
                .forEach(r => console.log(`- ${r.name}: ${r.error}`));
        }
    }
}

And performance monitoring once it’s live:

// Performance monitoring for API integrations
class APIPerformanceMonitor {
    constructor(options = {}) {
        this.metrics = new Map();
        this.alertThresholds = options.alertThresholds || {
            responseTime: 5000, // 5 seconds
            errorRate: 0.1, // 10%
            availability: 0.95 // 95%
        };
        this.monitoringInterval = options.monitoringInterval || 60000; // 1 minute
        this.startMonitoring();
    }

    // Record API call metrics
    recordAPICall(endpoint, method, duration, success, error = null) {
        const key = `${method}:${endpoint}`;
        
        if (!this.metrics.has(key)) {
            this.metrics.set(key, {
                totalCalls: 0,
                successfulCalls: 0,
                totalDuration: 0,
                errors: [],
                lastCall: null
            });
        }

        const metric = this.metrics.get(key);
        metric.totalCalls++;
        metric.totalDuration += duration;
        metric.lastCall = Date.now();

        if (success) {
            metric.successfulCalls++;
        } else {
            metric.errors.push({
                timestamp: Date.now(),
                error: error?.message || 'Unknown error',
                duration
            });
        }

        // Check for alerts
        this.checkAlerts(key, metric);
    }

    checkAlerts(endpoint, metric) {
        const avgResponseTime = metric.totalDuration / metric.totalCalls;
        const errorRate = (metric.totalCalls - metric.successfulCalls) / metric.totalCalls;

        if (avgResponseTime > this.alertThresholds.responseTime) {
            this.triggerAlert('HIGH_RESPONSE_TIME', endpoint, {
                avgResponseTime,
                threshold: this.alertThresholds.responseTime
            });
        }

        if (errorRate > this.alertThresholds.errorRate) {
            this.triggerAlert('HIGH_ERROR_RATE', endpoint, {
                errorRate,
                threshold: this.alertThresholds.errorRate
            });
        }
    }

    triggerAlert(type, endpoint, data) {
        const alert = {
            type,
            endpoint,
            timestamp: Date.now(),
            data
        };

        console.warn('API Performance Alert:', alert);
        
        // Send to monitoring service
        if (window.applicationInsights) {
            window.applicationInsights.trackEvent({ name: 'APIPerformanceAlert' }, alert);
        }
    }

    getMetricsSummary() {
        const summary = {};
        
        for (const [endpoint, metric] of this.metrics.entries()) {
            summary[endpoint] = {
                totalCalls: metric.totalCalls,
                successRate: metric.successfulCalls / metric.totalCalls,
                avgResponseTime: metric.totalDuration / metric.totalCalls,
                recentErrors: metric.errors.slice(-10), // Last 10 errors
                lastCall: metric.lastCall
            };
        }

        return summary;
    }

    startMonitoring() {
        setInterval(() => {
            this.cleanupOldMetrics();
            this.generatePerformanceReport();
        }, this.monitoringInterval);
    }

    cleanupOldMetrics() {
        const oneHourAgo = Date.now() - (60 * 60 * 1000);
        
        for (const [endpoint, metric] of this.metrics.entries()) {
            // Remove old errors
            metric.errors = metric.errors.filter(
                error => error.timestamp > oneHourAgo
            );
        }
    }

    generatePerformanceReport() {
        const summary = this.getMetricsSummary();
        
        // Log performance metrics
        console.log('API Performance Report:', summary);
        
        // Send to analytics
        if (window.applicationInsights) {
            window.applicationInsights.trackEvent({ name: 'APIPerformanceReport' }, summary);
        }
    }
}

// Integration with API clients
class MonitoredAPIClient extends RateLimitedAPIClient {
    constructor(baseURL, accessToken, options = {}) {
        super(baseURL, accessToken, options);
        this.performanceMonitor = new APIPerformanceMonitor(options.monitoring);
    }

    async request(endpoint, options = {}) {
        const startTime = Date.now();
        const method = options.method || 'GET';
        
        try {
            const result = await super.request(endpoint, options);
            const duration = Date.now() - startTime;
            
            this.performanceMonitor.recordAPICall(endpoint, method, duration, true);
            return result;
        } catch (error) {
            const duration = Date.now() - startTime;
            
            this.performanceMonitor.recordAPICall(endpoint, method, duration, false, error);
            throw error;
        }
    }

    getPerformanceMetrics() {
        return this.performanceMonitor.getMetricsSummary();
    }
}

Things worth getting right in production

On security: keep API keys in Key Vault or environment variables and never in source, rotate them on a schedule, grant the least access that works, and watch how they’re used. Validate and sanitise everything before it goes out. HTTPS always, modern TLS, and certificate pinning where the risk justifies it.

On performance: cache at several levels with TTLs that match how fast the data changes, batch requests where the API allows it, paginate large datasets, deduplicate identical in-flight requests, and keep an eye on how many concurrent connections you’re holding open.

On observability: log requests and responses with correlation IDs so you can trace one user’s journey across systems, track response times and error rates and throughput, alert on thresholds, and use distributed tracing once more than two systems are involved.

Wrapping up

Good integrations are mostly about what happens when things go wrong. Modern patterns on the client, credentials on the server, circuit breakers and retries around anything you don’t control, caching to keep it fast, and monitoring so you find out before your users do.

Next: third-party integrations and enterprise connectivity, building on all of this.