# Learn how YOU can build a Serverless GraphQL API on top of a Microservice

Follow me on Twitter, happy to take your suggestions on topics or improvements /Chris

This is when we take our Microservices, our GraphQL API, host that in a Serverless app and bring it all to production. Yes, it's a 15 min read, but what you get for it is something you can build on for your own projects. It is worth the read and plenty of pictures on the way. I hope you stay with me 😃

This is part of series:

This is the second part of our GraphQL, Serverless, Docker and Microservices series. Up to this point we have created Microservices, Dockerized those and was able to use the URL from those services when we stitched together our GraphQL API. That's an accomplishment in itself, however, we are not happy with that. We want to go to production - we want to go to the Cloud.

I highly recommend reading the first part of the series, First part

If you have, let's rock !

The Plan

We've mentioned the plan in part I. But here it is again

  1. Create microservices, part I
  2. Dockerize services, part I
  3. Create graphql api and have the resolve functions point to the url of each dockerized service, part I
  4. Create a serverless function, this part
  5. Deploy the our microservices to the Cloud, this part
  6. Add our graphql api to our serverless function, this part
  7. Deploy serverless function to the cloud, this part

The first three items have been completed in the first part of our services, now it's time to tackle the remaining four items

Resources

You can definitely follow this guide without reading these links but learn more details on deploy options and how to build out Serverless or how to deploy your containers in Azure I recommend looking through these links:

Project structure

Let's remind ourselves where we are with our project structure so we are on the same page moving forward. We should have the following:

/graphql-api
  /products  // our product service
  /reviews // our reviews service
  /serverless // will contain our serverless function
  docker-compose.yml
1
2
3
4
5

Create a serverless function

To create our Function we first need a Function app to host it in. Before we get that far, let's ensure we've installed all the prerequisites we need. This looks a bit different on Mac and Windows. Let's start with Mac and open up a terminal and enter:

brew tap azure/functions
brew install azure-functions-core-tools
1
2

If you are lacking brew, refer to this link to have it installed.

For Windows we just need Node.js installed and then we open up a terminal and enter:

npm install -g azure-functions-core-tools@2
1

We also need to install a Visual Studio Code extension to make scaffolding, debugging and deployment of our Azure function a breeze, so let's do that next. Click the extension's icon in VS Code and look for Azure Functions and select to install it.

Scaffold a project

Our next step is to create an Azure App, we do so by pressing COMMAND + SHIFT + P or CTRL+SHIFT+P for Windows. This should bring up a menu looking like this:

Thereafter you select the indicated command above and you are now presented with the following below.

You can select whatever folder you want but know that it will create a folder .vscode in the workspace you are currently in. .vscode contains a bunch of files making debugging of this project possible. I select the serverless folder and I also ensure VS Code has opened that folder so that my .vscode folder is created in the right place.

We go with Javascript this time. Next screen is to choose a trigger, that is, what event will lead to this code to be executed:

Next step is giving the Azure function a name. Yes, it not only creates an Azure app project for us but it also creates one function that it starts out with. We can always add more functions later if we wish.

I choose the name graphql. There, just one more step, Authorization level. There are three ways to authorize the usage of our app, Anonymous, Function and Admin. With Anonymous anyone can call our API and we don't need to send any extra credentials. With Function we need to send a function key as a header and with Admin it's even more things we need to do, to be able to be allowed to call the function. We settle for the option Anonymous as we, for now, want to make this easier to test. We should definitely revisit this choice as we progress building out our app. If it's a toy app Anonymous is fine but in a production scenario, you probably want to have Function or Admin as options.

At this point you should have the following project structure:

Debug

Let's make sure that our serverless function is correctly created by trying to debug it. Place a breakpoint in your index.js file like so:

and now let's go the Debug menu, like so:

This should start up the function and write a lot of things to the terminal and it should end with a URL printout looking like this:

So we go and visit the indicated URL http://localhost:7071/api/graphql in a browser and this should lead to our breakpoint being hit:

Good, everything is working. We can now go to the next step, which is to take our Graphql API implementation and call it from our serverless function.

Adding the Graphql API to our Serverless app

Ok, add this point we need to make our created GraphQL part of our serverless app. To make that happen we need to move some files. We need to copy in the package.json file to the root of our serverless function project. When we create a project using VS Code it will run npm install for us, providing it finds a package.json at the right level. The rest of the GraphQL API we can easily copy in as a subdirectory under our serverless directory. It should now look like this:

As you can see above our GraphQL API directory api has been copied in and it now only consists of the files app.js, raw-schema.js and services.js. We have moved package.json and the .env file to the root of the serverless project.

Import our GraphQL API

At this point, we can start importing and calling the GraphQL code from our Serverless function. Let's open the graphql directory, where our function lives and open up index.js and start adding an import statement to our GraphQL API, like so:

// /graphql/index.js

const { graphql, schema } = require('../api');

// the rest omitted for brevity
1
2
3
4
5

The above means we are importing a file ../api.index.js. We didn't create one in the past so we need to do that:

// ../api.index.js

const {
  graphql
} = require('graphql');
const rawSchema = require('./raw-schema');

require('dotenv').config()

module.exports = {
  schema: rawSchema,
  graphql
}
1
2
3
4
5
6
7
8
9
10
11
12
13

Call the Graphql API from our serverless function

What now, how do we want to call our Serverless function? Well, we want to read a GraphQL query from either a query parameter our from the body.

Before we come that far let's ensure we can spin up our Serverless function, call our GraphQL API with a static query and get some result. So change the content of serverless/graphql/index.js to the following:

const { graphql, schema } = require('../api')

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    const query = `{ hello products { name, description } reviews { title, comment, grade, product { name, description } } }`;

    const result = await graphql({
        schema,
        source: query
    })
    context.res = {
        // status: 200, /* Defaults to 200 */
        body: result
    };
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Let's ensure we have done the following before we proceed to test our implementation:

  1. Ran npm install, we need to ensure we have installed, graphql, dotenv, node-fetch
  2. Ran docker-compose up -d, we need to spin up our services that our GraphQL API queries
  3. Add code calling the GraphQL API
  4. Debug Serverless function

When we've done steps 1-4 we are ready to debug. So let's select Debug/ Start Debugging

At this point we have something that we can test locally, so let's do just that:

Ok, we can see it seems to work. Now that the time has come to prepare for deploy.

Deploy our app to Azure

Looking at it from a higher level there are some things we need to do. Our solution consists of two major parts, our microservices and our Serverless app that calls a GraphQL API. For our deployment to Cloud to work we need to deploy those parts separately. Let's list what we need to do and why:

## Deploy the microservices to the Cloud The microservices needs to be created as service endpoints. Because we are already using Docker lets leverage that and continue using Docker but in the cloud. How do you ask? This is how:

  1. Build the Docker images locally
  2. Create a container registry in the Cloud, we will push our images to this registry. The reason is that our Container Registry is able to hold the images as a repository but it is also able to create containers from those images, provided they are inside the registry. Once we create containers from those images this will create service endpoints. Each service endpoint will receive a unique URL. We can use those URLs we get from the Cloud and have our Serverless/GraphQL solution point to those URLs instead of our local URLs
  3. Tag images, before we can push each Docker image to our container registry in the Cloud we need to tag it with credentials from the Container registry. Then it's a simple push command to make the images end up in the registry.
  4. Create service endpoints, when the Docker images are in our registry in the Cloud it's really simple to create containers from them, this will create service endpoints with a real URL, one for each service. We want the Serverless app and its GraphQL API to point to those endpoints

Create container registry

We might need a resource group first if we don't have one we want to use for this. I recommend having a specific resource group for everything that goes together, web apps, services, accounts, etc. Here is the syntax for creating a Resource Group from the terminal:

az group create --name [name of resource group] --location westeurope
1

At this point you are ready to create the container registry:

az acr create --resource-group [name of resource group] --name [name of container registry, unique and only a-z or 0-9] --sku Basic --admin-enabled true
1

The above will create a container registry, using your existing resource group and it will also give your container registry a name and a price tier Basic.

Build and tag Images

Building images id a simple as running a Docker command. We do this twice, once for each service. We can either place ourselves in each service directory, where the Dockerfile is or we need to specify for each image creation where each of the Dockerfiles is located. We do the former, that is place ourselves in each Dockerfile containing directory:

// in /products

docker build -t products-service .

// in /reviews

docker build -t reviews-service .
1
2
3
4
5
6
7

Above we are giving it the name product-service and reviews-service respectively. At this point, we are ready to tag the images, so our container registry recognizes them. To do so we need a piece of information from the container registry that we need to tag our image with. The information we are looking for is called the loginServer. There are two ways we can come by this information, both ways work:

  1. Log in to the container registry and query for that property
  2. Create it by merging the container registry name with a preset domain

Let's do 1) first:

az acr login --name [name of registry]
1

This will log us into the registry and we are ready to query it for the information we need:

az acr show --name [name of container registry] --query loginServer --output table
1

Above we are actively querying for loginServer and the result of this is our loginServer.

The second option 2) is realizing we can guess this information by merging [name of registry].azurecr.io. As the domain might differ in the future I would say querying for loginServer is the more future safe way of doing it.

Tag the images

Ok, time to tag our images:

docker tag products-service [loginServer]/products-service:v1
1

and then one more time for the other service:

docker tag reviews-service [loginServer]/reviews-service:v1
1

Push images to the Cloud

Ok, finally we are ready to push the images to the container registry. This is as easy as typing:

docker push [loginServer]/products-service:v1
1

and now for the review-service:

docker push [loginServer]/reviews-service:v1
1

I'm not gonna lie, this takes time if you sit at home. At least for me sitting on a connection that has fast download and slow upload. Try doing this step on a company WiFi, or good home WiFi at the least the first time. The next time you do it it will be fast it is able to cache some of the layers in the image. We can see that caching in action already when we push the reviews-service as they are very similar and uses the same image and other things:

Verify our upload

How do we know the images are actually in the registry, in our Cloud? We can query for them, like so:

Above we are running the command:

az acr repository list --name [name of registry] --output table
1

And the result is our products-service and our reviews-service. This is our images, but this time residing in the Cloud, in our container registry.

Create service endpoints

There are two ways of doing this:

  1. We keep using the terminal and we run a command that creates a service endpoint/container for each image
  2. We use the Portal UI and select an App Service template that selects the right image

The terminal Yes, you can be using the Terminal here and below are the commands to make that happen. For this, especially as we are deploying for the first time I would recommend you use the alternate version, the Portal UI so you see visually what's going on.

az acr show --name --query loginServer
1

Then we get password and username

az acr credential show --name --query "passwords[0].value"
1

Then we finally push:

az container create --resource-group [resource group] --name aci-tutorial-app --image <acrLoginServer>/[products-service or reviews-service]] --cpu 1 --memory 1 --registry-login-server [acrLoginServer] --registry-username [acrName] --registry-password [acrPassword] --dns-name-label [aciDnsLabel] --ports 80
1

The portal UI This is the one that I use the most, I have to admit. I'm a creature of habit. We start with our usual create a resource button:

Thereafter we need to choose a Web template that takes containers, this one:

Thereafter we need to fill in some mandatory fields:

The App name needs to be globally unique. Select the Subscription you want should be billed. Select the existing Resource Group you've just created. Select the appropriate App Service plan. Lastly, click Configure container, now it's time to select the correct container registry and image we want to create a container from.

Here we are choosing the registry we created chrisgraphqlregistry, in your case, choose your created registry. Next up we choose the image products-service, followed by the tag v1 and lastly we select our startup file app.js. Finally, we click Apply and this takes us back to our previous dialog and here we press Create. At this point, it provisions a service endpoint that when done will tell us the resulting URL.

Once we click the provisioned resource, search for the App name you gave it. You should come to a screen like this:

Now follow these exact instructions and do the same but create a service endpoint for the reviews-service.

The first time you click either of the URL it takes a while, a so-called cold start. Once it's ready the result should look like this, for the products-service:

and like this for the reviews-service:

This means that we have successfully deployed our services and we are about 90% there. Wasn't too bad, was it? 😃

Deploy the Serverless app

Ok we need to do two things to deploy our serverless app:

  1. Ensure the app reads its environment variables from the Cloud
  2. Deploy the app, using VS Code

Using local.settings.json over .env

Right now we have the library dotenv read in environment variables from a .env file. This won't do when we are going to the Cloud. We need to read this from the AppSettings property of our Serverless app, once it is in the Cloud. The file local.setting.json can take its contents and copy itself into the AppSettings property so by populating that file we can ensure our environment variables end up in the Cloud.

Now that we have deployed the services successfully to the Cloud let's create a file called local.settings.json in our Serverless app and have the content look like this with the service endpoint URLs filled in:

// local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "PRODUCTS_URL": "https://products-service-container.azurewebsites.net/",
    "REVIEW_URL": "https://reviews-service-container.azurewebsites.net/"
  }
}
1
2
3
4
5
6
7
8
9

At this point we can go into serverless/api/index.js and remove the line that says:

require('dotenv').config()
1

cause now we are reading from local.settings.json. Now run the debugger. Go to your browser and it should still work at http://localhost:7071/api/graphql.

### Deploying the Serverless app This means we are ready for that final deploy step. Are you ready? Now I mean ready ready? Good, ok, let's do it 😃

At this point, we need to interact with the Azure view. If you can't see it then take View / Open View, like so:

Then select to sign in to Azure, like so:

This will take you to a browser page that asks you to sign in. Once that is done, head back to VS Code and select the following:

Ok, at this point you are asked to select a subscription. After that, you come to this dialog . Click to create a new Function app in the Azure.

Lastly, you are asked to give the app a name. It needs to be globally unique. At this point, it will start to provision. It will show something like this while we wait for it to finish:

When done it will show you this:

Ok, let's click View Output:

The first time you look at this the output might state that it has no knowledge of PRODUCTS_URL and REVIEWS_URL but we can fix that in our Azure menu, like so:

After that. Head to the portal again. Click get function URL:

and this time you should see this in the browser:

We did it. We deployed the services to the Cloud, we deployed the serverless app.

Final touch

Right now we are hardcoding what the query is that we send to our GraphQL API, so let's fix that and redeploy. The code should look like this now:

// serverless/graphql/index.js

const { graphql, schema } = require('../api')

module.exports = async function (context, req) {
    context.log('Products url', process.env.PRODUCTS_URL);
    context.log('Reviews url', process.env.REVIEW_URL);

    context.log('JavaScript HTTP trigger function processed a request.');

    const query = req.query.query || (req.body && req.body.query);

    if(!query) {
        context.res = {
            status: 400,
            body: "You must send `query` as a query parameter or in the body"
        };
    }

    const result = await graphql({
        schema,
        source: query
    })
    context.res = {
        // status: 200, /* Defaults to 200 */
        body: result
    };
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Now, redeploy

It should look like this:

Ok, it seems to be working, it fails if it doesn't get a query param. Let's give it one query and let's assign it with the query { reviews { grade, product { name } } }

## Summary

There we have it, boys and girls. A working Serverless/GRaphQL API that talks to Microservices, also in the Cloud. How excited are you? I'm this excited:

We started off with separate microservices. Dockerized those and ensured each service could be reachable through a URL. At that point, we started building a GraphQL API and started querying those services as a way to stitch together data which is one of the advantages of GraphQL to be that API on top of many other APIs.

In this part, we went and put those services in the Cloud. We also created a Serverless App and pulled in our GraphQL API, that was also sent to the Cloud and suddenly everything is in the Cloud and can be maintained and redeployed separately. We are set up in a great way to expand our GraphQL API and we are really using the advantage of Serverless, we focus on writing code and ensure that we don't pay for more than we use.