How to Build Scalable APIs Using GraphQL and Serverless

How to Build Scalable APIs Using GraphQL and Serverless

In this GraphQL and Serverless tutorial, you'll learn how to build Scalable APIs Using GraphQL and Serverless. Exploring Serverless API, we will have a look at the more advanced features and standards around mutators and resolvers and then she will close by going all in, full Serverless and deploy a GraphQL server to a function in the cloud.

Current trends in software and backend architecture have been evolving towards a more loosely coupled, more granular design. Most of you have heard of micro-service based architectures; the latest development in the past couple of years has been the advent of Serverless which allows you to run applications in very cost effective ephemeral services.

This is why it is important to have a proper gateway for your API that is able to route all your requests to the designated endpoint. GraphQL stands out in that respect as being a mature open sourced standard started at Facebook. Simona will demonstrate how to set up a GraphQL server locally, then explore the Query language and schema definitions it provides which allows you essentially query your mesh of services from a single point of entry.

The beauty is that it will notify you early if any of your endpoints is misbehaving or the schemas are out of date by erring out. Another advantage is that it allows for your API documentation to be a real time process and it will give you what one may call an API playground where you can query and explore your API. After exploring Serverless API, Simona will have a look at the more advanced features and standards around mutators and resolvers and then she will close by going all in, full Serverless and deploy a GraphQL server to a function in the cloud.

Advanced patterns for GitHub's GraphQL API

Advanced patterns for GitHub's GraphQL API

Advanced patterns for GitHub's GraphQL API. The GitHub API is a key part of accelerating workflows at scale. This GraphQL API will leave you with tactical tips for how to paginate effectively, create and plan queries, use tech-preview features, and manage costs learned from years of practice and iteration at Toast and beyond.

The GitHub API is a key part of accelerating workflows at scale. This GraphQL API will leave you with tactical tips for how to paginate effectively, create and plan queries, use tech-preview features, and manage costs learned from years of practice and iteration at Toast and beyond.

How to build Scalable APIs using GraphQL and Serverless

How to build Scalable APIs using GraphQL and Serverless

GraphQL and Serverless Tutorial: Learn how to build Scalable APIs using GraphQL and Serverless

GraphQL is a different way to connect your client applications to your backend. In general, we are used to REST, where the client connects to the backend via a defined endpoint. When connecting to an endpoint, the client needs to specify headers, an HTTP method (GET, POST, DELETE, etc.), a body, and all kinds of parameters. Usually, he needs to be familiar with all the information beforehand to be able to request the information from the server. The client might end up getting a lot of information back that isn’t needed (over fetch) and often forces him to do a lot of calls to the backend to populate a view since one request only brings part of the information needed (under fetch).

GraphQL has some important characteristics. Between the client and the server, a contract is signed, called the GraphQL schema. Here, all possible types of operations that the client can perform on the backend are defined. The client can call an operation with one request, which will return multiple types if needed so that there is no under fetch of information. The client can also specify attributes for the types it wants so that there is no over fetch of information.

GraphQL is implemented between the client and the data sources, making GraphQL a single entry point to the backend. The data sources can be anything from NoSQL databases, relational databases, and HTTP servers to whatever returns data. To connect a GraphQL implementation to the data sources, you need to write resolvers. Resolvers are a very important part of your GraphQL application, as they are the ones that translate GraphQL requests or responses to whatever the data sources understand. For example, if the data source is a relational database, the resolver will need to know how to transform a GraphQL query into a SELECT operation and then translate whatever the relational database returns into a GraphQL response.

Current trends in software and backend architecture have been evolving towards a more loosely coupled more granular design. I am sure most of you have heard of microservice based architectures. The latest development on that front in the past couple of years has been the advent of Serverless which allows you to run applications in very cost effective ephemeral services. This is why it is important to have a proper gateway for your API that is able to route all your requests to the designated endpoint.

GraphQL stands out in that respect as being a mature open sourced standard started at Facebook. We will first have a look at how we set up our own GraphQL server locally, then we will explore the Query language and schema definitions it provides which allows you essentially query your mesh of services from a single point of entry. The beauty of that is it will notify you early if any of your endpoints is misbehaving or the schemas are out of date by erring out. Another advantage of this is that it allows for your API documentation to be a real time process and it will give you what one may call an API playground where you can query and explore your API.

After we explore our Serverless API we will have a look at the more advanced features and standards around mutators and resolvers and then we will close by going all in, full Serverless and deploy our GraphQL server to a function in the cloud.

Speakers:
Simona Cotin - Senior Cloud Advocate, Microsoft
Matteo Collina - Technical Director, NearForm

Source Code: https://mybuild.techcommunity.microsoft.com/VideoDownloader/Download-BuildResources.zip

Building Microservices and a GraphQL API with Docker

Building Microservices and a GraphQL API with Docker

Learn how you can use Docker to build Microservices with Docker Compose as part of building and Cloud Hosted API: Building Microservices and a GraphQL API, Hosting the GraphQL API in a Serverless app and bring it all to the Cloud.

The idea with this article is to show how we can build microservices, dockerize them and combine them in a GraphQL API and query it from a Serverless function, how's that for a lot of buzzwords in one? ;) Microservices, Docker, GraphQL, Serverless

This is part of series:

  • Building Microservices and a GraphQL API, Part I
  • Hosting the GraphQL API in a Serverless app and bring it all to the Cloud, Part II

So, it's quite ambitious to create Microservices, Serverless and deploy to the Cloud in one article so this is a two-parter. This is part one. This part deals with Microservices and GraphQL. In part two we make it serverless and deploy it.

Building Microservices and a GraphQL API, Part I

In this article we will cover:

  • GraphQL and Microservices, these are two great paradigms that really go quite well together, let's explain how
  • Building Microservices and Dockerizing them, let's create two micros services, each with their own areas of responsibility and let's Dockerize them
  • Implementing GraphQl, we will show how we can define a GraphQL backend with schema and resolver and how to query it, of course, we will also tie in our Micro services here
GraphQL and Microservices

A library and paradigm like GraphQL, is the most useful when it is able to combine different data sources into one and serve that up as one unified API. A developer of the Front end app can then query the data they need by using just one request.

Today it becomes more common to break down a monolithic architecture into microservices, thereby you get many small APIs that works independently. GraphQL and microservices are two paradigms that go really well together. How you wonder? GraphQL is really good at describing schemas but also stitch together different APIs and the end result is something that's really useful for someone building an app as querying for data will be very simple.

Different APIs is exactly what we have when we have a Microservices architecture. Using GraphQL on top of it all means we can reap the benefits from our chosen architecture at the same time as an App can get exactly the data it needs.

How you wonder? Stay with me throughout this article and you will see exactly how. Bring up your code editor cause you will build it with me :)

The plan

Ok, so what are we building? It's always grateful to use an e-commerce company as the target as it contains so many interesting problems for us to solve. We will zoom in on two topics in particular namely products and reviews. When it comes to products we need a way to keep track of what products we sell and all their metadata. For reviews we need a way to offer our customer a way to review our products, give it a grade, a comment and so on and so forth. These two concepts can be seen as two isolated islands that can be maintained and developed independently. If for example, a product gets a new description there is no reason that should affect the review of said product.

Ok, so we turn these two concepts into product service and a review service.

Data structure for the services

What does the data look like for these services? Well they are in their infancy so let's assume the product service is a list of products for now with a product looking something like this:

[{
  id: 1,
  name: 'Avengers - infinity war',
  description: 'a Blue-ray movie'
}]

The review service would also hold data in a list like so:

[{
  id: 2,
  title: 'Oh snap what an ending',
  grade: 5,
  comment: 'I need therapy after this...',
  product: 1
}]

As you can see from the above data description the review service holds a reference to a product in the product service and it's by querying the product service that you get the full picture of both the review and the product involved.

Dockerizing

Ok, so we understand what the services need to provide in terms of a schema. The services also need to be containerized so we will describe how to build them using Docker a Dockerfile and Docker Compose.

GraphQL

So the GraphQL API serves as this high-level API that is able to combine results from our product service as well as review service. It's schema should look something like this:

type Product {
   id: ID,
   name: String,
   description: String
}

type Review {
  id: ID,
  title: String,
  grade: Int,
  comment: String,
  product: Product
} 

type Query {
  products: [Product]
  reviews: [Review]
 }

We assume that when a user of our GraphQL API queries for Reviews they want to see more than just the review but also some extra data on the Product, what's it called, what it is and so on. For that reason, we've added the product property on the Review type in the above schema so that when we drill down in our query, we are able to get both Review and Product information.

Serverless

So where does Serverless come into this? We need a way to host our API. We could be using an App Service but because our GraphQL API doesn't need to hold any state of its own and it only does a computation (it assembles a result) it makes more sense to make it a light-weight on-demand Azure Function. So that's what we are going to do :) As stated in the beginning we are saving this for the second part of our series, we don't want to bore you by a too lengthy article :)

Creating and Dockerizing our Microservices

We opt for making these services as simple as possible so we create REST APIs using Node.js and Express, like so:

/products
  app.js
  Dockerfile
  package.json
/reviews
  app.js
  Dockerfile
  package.json

The app.js file for /products looks like this:

// products/app.js

const express = require('express')
const app = express()
const port = process.env.PORT || 3000

app.get('/', (req, res) => res.json([{
  id: "1",
  name: 'Avengers - infinity war',
  description: 'a Blue ray movie'
}]))
app.listen(port, () => console.log(`Example app listening on port port!`))

and the app.js for /reviews looks like this:


// reviews.app.js

const express = require('express')
const app = express()
const port = process.env.PORT  || 3000

app.get('/', (req, res) => res.json([{
  id: "2",
  title: 'Oh snap what an ending',
  grade: 5,
  comment: 'I need therapy after this...',
  product: 1
}]))
app.listen(port, () => console.log(`Example app listening on port port!`))

Looks almost the same right? Well, we try to keep things simple for now and return static data but it's quite simple to add database later on.

Dockerizing

Before we start Dockerizing we need to install our dependency Express like so:

npm install express

This needs to be done for each service.

Ok, we showed you in the directory for each service how there was a Dockerfile. It looks like this:

// Dockerfile

FROM node:latest
WORKDIR /app
ENV PORT=3000
COPY . .
RUN npm install
EXPOSE $PORT
ENTRYPOINT ["npm", "start"]

Let's go up one level and create a docker-compose.yaml file, so it's easier to create our images and containers. Your file system should now look like this:

docker.compose.yaml
/products
  app.js
  Dockerfile
  package.json
/reviews
  app.js
  Dockerfile
  package.json

Your docker-compose.yaml should have the following content:

version: '3.3'
services: 
  product-service:
    build:
      context: ./products
    ports:
      - "8000:3000"
    networks: 
      - microservices
  review-service:
    build:
      context: ./reviews
    ports:
      - "8001:3000"
    networks:
      - microservices
networks: 
  microservices:

We can now get our service up and running with

docker-compose up -d

I always feel like I'm starting up a jet engine when I run this command as all of my containers go up at the same time, so here goes, ignition :)

You should be able to find the products service at http://localhost:8000 and the reviews service at http://localhost:8001. That covers the microservices for now, let's build our GraphQL API next.

Your products service should look like the following:

and your review service should look like this:

Implementing GraphQL

There are many ways to build a GraphQL server, we could be using the raw graphql NPM library or the express-graphql, this will host our server in a Node.js Express server. Or we could be using the one from Apollo and so on. We opt for the first one graphql as we will ultimately serve it from a Serverless function.

So what do we need to do:

  1. Define a schema
  2. Define services we can use to resolve different parts of our schema
  3. Try out the API

Define a schema

Now, this is an interesting one, we have two options here for defining a schema, either use the helper function buildSchema() or use the raw approach and construct our schema using primitives. For this case, we will use the raw approach and the reason for that is I simply couldn't find how to resolve things at depth using buildSchema() despite reading through the manual twice. It's strangely enough easily done if we were to use express-graphql or Apollo so sorry if you feel your eyes bleed a little ;)

Ok, let's define our schema first:

// schema.js

const { 
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLInt,
  GraphQLNonNull,
  GraphQLList,
  GraphQLString
} = require('graphql');

const {
  getProducts,
  getReviews,
  getProduct
} = require('./services');

const reviewType = new GraphQLObjectType({
  name: 'Review',
  description: 'A review',
  fields: () => ({
    id: {
      type: GraphQLNonNull(GraphQLString),
      description: 'The id of Review.',
    },
    title: {
      type: GraphQLString,
      description: 'The title of the Review.',
    },
    comment: {
      type: GraphQLString,
      description: 'The comment of the Review.',
    },
    grade : {
      type: GraphQLInt
    },
    product: {
      type: productType,
      description: 'The product of the Review.',
      resolve: (review) => getProduct(review.product) 
    }
  })
})

const productType = new GraphQLObjectType({
  name: 'Product',
  description: 'A product',
  fields: () => ({
    id: {
      type: GraphQLNonNull(GraphQLString),
      description: 'The id of Product.',
    },
    name: {
      type: GraphQLString,
      description: 'The name of the Product.',
    },
    description: {
      type: GraphQLString,
      description: 'The description of the Product.',
    }
  })
});

const queryType = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    hello: {
      type: GraphQLString,
      resolve: (root) => 'world'
    },
    products: {
      type: new GraphQLList(productType),
      resolve: (root) => getProducts(),
    },
    reviews: {
      type: new GraphQLList(reviewType),
      resolve: (root) => getReviews(),
    }
  }),
});

module.exports = new GraphQLSchema({
  query: queryType,
  types: [reviewType, productType],
});

Above we are defining two types Review and Product and we expose two query fields products and reviews.

I want you to pay special attention to the variable reviewType and how we resolve the product field. Here we are resolving it like so:

resolve: (review) => getProduct(review.product) 

Why do we do that? Well, it has to do with how data is stored on a Review. Let's revisit that. A Review stores its data like so:

{
  title: ''
  comment: '',
  grade: 5
  product: 1
}

As you can see above the product field is an integer. It's a foreign key pointing to a real product in the product service. So we need to resolve it so the API can be queried like so:

{
  reviews {
    product { 
      name
    }
  }
}

If we don't resolve product to a product object instead the above query would error out.

Create services

In our schema.js we called methods like getProducts(), getReviews() and getProduct() and we need those to exist so we create a file services.js, like so:

const fetch = require('node-fetch');

const getProducts = async() => {
  const res = await fetch(process.env.PRODUCTS_URL)
  const json = res.json();
  return json;
}

const getProduct = async(product) => {
  const products = await getProducts()
  return products.find(p => p.id == product);
} 

const getReviews = async() => {
  const res = await fetch(process.env.REVIEW_URL)
  const json = res.json();
  return json;
}

module.exports = {
  getProducts,
  getReviews,
  getProduct
}

Ok, we can see above that methods getProducts() and getReviews() makes HTTP requests to URL, at least judging by the names process.env.PRODUCTS_URL and process.env.REVIEW_URL. For now, we have created a .env file in which we create those two env variables like so:

PRODUCTS_URL = http://localhost:8000
REVIEW_URL = http://localhost:8001

Wait, isn't that? Yes, it is. It is the URLs to product service and review service after we used docker-compose to bring them up. This is a great way to test your Microservice architecture locally but also prepare for deployment to the Cloud. Deploying to the Cloud is almost as simple as switching these env variables to Cloud endpoints, as you will see in the next part of this article series :)

Trying out our GraphQL API

Ok, so we need to try our code out. To do that let's create an app.js file in which we invoke the graphql() function and let's provide it our schema and query, like so:

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

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

graphql({
  schema: rawSchema,
  source: query
}).then(result => {
  console.log('result', result);
  console.log('reviews', result.data.reviews);
})

In the above code, we specify a query and we expect the fields hello, products and reviews to come back to us and finally we invoke graphql() that on the then() callback serves up the result. The result should look like this:

Summary Pat I

We set out on a journey that would eventually lead us to the cloud. We are not there yet but part two will take us all the way. In this first part, we've managed to create microservices and dockerize them. Furthermore, we've managed to construct a GraphQL API that is able to define a schema that merges our two APIs together and serve that up.

What remains to do, that will be the job of the second part, is to push our containers to the cloud and create service endpoints. When we have the service endpoints we can replace the value of environment variables to use the Cloud URLs instead of the localhost ones we are using now.

Hosting the GraphQL API in a Serverless app and bring it all to the Cloud, Part II 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

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

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 [email protected]

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

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
}

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
    };
};

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

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

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 .

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]

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

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

and then one more time for the other service:

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

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

and now for the review-service:

docker push [loginServer]/reviews-service:v1

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

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

Then we get password and username

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

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

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/"
  }
}

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

require('dotenv').config()

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
    };
};

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 Part II

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.