Building a JAMStack App with CloudFlare Workers and AthenaHealth APIs - Part 1

Part One - Go to Part Two

In part one of this two-post blog entry, we will walk you through the process of creating a JAMStack application using CloudFlare Workers and AthenaHealth APIs. We will build a simple app that fetches data from the AthenaHealth API, caches the data, and displays it using CloudFlare Workers. The app will include paths for fetching department and provider information.

Ready to elevate your medical practice? Let's connect.

Overview of Cloudflare Workers and AthenaHealth APIs:

Cloudflare Workers is a serverless platform that allows you to build and deploy applications at the edge. It enables developers to write JavaScript code that runs directly in Cloudflare's global network of data centers, ensuring low latency and high performance. The Cloudflare Workers documentation provides a comprehensive guide, including detailed API references, examples, and tutorials to help you get started and make the most of the platform.

AthenaHealth provides a suite of APIs to access and interact with healthcare data. In this tutorial, we will use the Departments API https://docs.athenahealth.com/api/api-ref/departments#Departments and the Providers API https://docs.athenahealth.com/api/api-ref/provider#Provider to fetch and display information about departments and providers.

What is JAMStack?

JAMstack is a modern web development architecture focused on improving performance, scalability, and security. The acronym JAM stands for JavaScript, APIs, and Markup. The key principles of JAMstack are pre-rendering static assets, leveraging client-side JavaScript for interactivity, and utilizing APIs for server-side functionality.

In a JAMstack application, content is generated during the build process, creating static files that can be served directly from a Content Delivery Network (CDN). This approach reduces server load and latency, resulting in faster page load times and better user experience. The client-side JavaScript is responsible for dynamic behavior, making API calls to access data or perform server-side operations.

JAMstack promotes a decoupled architecture, which separates the frontend from the backend, enabling developers to use the best tools and technologies for each. This also simplifies the deployment process and makes scaling the application easier. JAMstack sites are inherently more secure, as there are fewer attack vectors due to the reduced reliance on server-side components.

Setting up Cloudflare Workers

To get started, sign up for a Cloudflare account if you don't already have one. Next, follow the instructions in the Cloudflare Workers documentation https://developers.cloudflare.com/workers to set up your environment and create your first worker.

Once your environment is set up, you will have a basic worker template similar to the following:

                            
    export default {
        async fetch(request, env, ctx) {
            return new Response("Hello World!");
        },
    };
                            
                        

Authenticating with AthenaHealth APIs

Before you can access the AthenaHealth APIs, you need to authenticate and obtain an access token. We will create a function called authenticate() that handles the authentication process, making a POST request to the API with the client credentials and returning the access token.

                            

    async function authenticate() {
        const url = `${ATHENA_BASE_URL}${AUTH_PATH}`;
        const auth = 'Basic ' + btoa(ATHENA_API_KEY + ':' + ATHENA_API_SECRET);
        const headers = new Headers({
            'Authorization': auth,
            'Content-Type': 'application/x-www-form-urlencoded',
        });
        const body = new URLSearchParams({
            grant_type: 'client_credentials',
            scope: 'athena/service/Athenanet.MDP.*',
        });

        const response = await fetch(url, { method: 'POST', headers, body });
        const json = await response.json();

        if (!json.access_token) {
            throw new Error('Missing token!');
        }

        return json.access_token;
    }
                            
                        

Fetching and Caching Data from AthenaHealth APIs

With the access token in hand, we can now fetch data from the Departments and Providers APIs. We will create two functions, fetchAthenaDepartments() and fetchAthenaProviders(), which will handle the process of fetching the data and caching it using Cloudflare Workers.

                            
    async function fetchAthenaDepartments(token) {
        const url = `${ATHENA_BASE_URL}/v1/${PRACTICE_ID}/departments`;
        const headers = new Headers({
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
        });

        const response = await fetch(url, { headers });
        return response.json();
    }

    async function fetchAthenaProviders(token) {
        const url = `${ATHENA_BASE_URL}/v1/${PRACTICE_ID}/providers`;
        const headers = new Headers({
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
        });

        const response = await fetch(url, { headers });
        return response.json();
    }
                            
                        

Creating Paths for Departments and Providers

In our Cloudflare worker, we will create paths for fetching department and provider information. Update the fetch function in the worker to handle the /departments and /providers paths, as well as a separate path for fetching a specific provider by ID, /provider/[id].

                            
    export default {
        async fetch(request, env, ctx) {
            const url = new URL(request.url);

            if (url.pathname === '/departments') {
                try {
                    const token = await authenticate();
                    const departments = await fetchAthenaDepartments(token);
                    return new Response(JSON.stringify(departments), {
                        headers: { 'Content-Type': 'application/json' },
                    });
                } catch (error) {
                    return new Response(error.message, { status: 500 });
                }
            }
            else if (url.pathname === '/providers') {
                try {
                    const token = await authenticate();
                    const providers = await fetchAthenaProviders(token);
                    return new Response(JSON.stringify(providers), {
                        headers: { 'Content-Type': 'application/json' },
                    });
                } catch (error) {
                    return new Response(error.message, { status: 500 });
                }
            }
            else {
                return new Response('Not Found', { status: 404 });
            }
        },
    };
                            
                        

Testing the Worker

To test the worker, you can use the wrangler command-line tool that comes with Cloudflare Workers. Run npx wrangler dev src/index.js in your terminal to start a development server, and open a browser tab at http://localhost:8787/ to see your worker in action.

Deploying the Worker

Finally, to deploy your worker, run npx wrangler publish src/index.js --name my-worker in your terminal.


In this tutorial, we started working on a JAMstack application using Cloudflare Workers and AthenaHealth APIs. The app, so far, fetches data from the Departments and Providers APIs and displays a JSON data response using separate paths in the worker. With this foundation in place, we will next start using the JAMStack approach to create an appealing User Interface and display our data ina more attractive way to our users.

Contact Us