Kian Wallace

Kian Wallace

1572236055

Building Microservices and a GraphQL API with Docker

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 azure-functions-core-tools@2

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.

#Microservices #Docker #GraphQL #API #Serverless

What is GEEK

Buddha Community

Building Microservices and a GraphQL API with Docker

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

Kian Wallace

Kian Wallace

1572236055

Building Microservices and a GraphQL API with Docker

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 azure-functions-core-tools@2

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.

#Microservices #Docker #GraphQL #API #Serverless

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Iliana  Welch

Iliana Welch

1595249460

Docker Explained: Docker Architecture | Docker Registries

Following the second video about Docker basics, in this video, I explain Docker architecture and explain the different building blocks of the docker engine; docker client, API, Docker Daemon. I also explain what a docker registry is and I finish the video with a demo explaining and illustrating how to use Docker hub

In this video lesson you will learn:

  • What is Docker Host
  • What is Docker Engine
  • Learn about Docker Architecture
  • Learn about Docker client and Docker Daemon
  • Docker Hub and Registries
  • Simple demo to understand using images from registries

#docker #docker hub #docker host #docker engine #docker architecture #api