Handling multiple serverless APIs with API gateway in Google Cloud

Prathmesh Patil
9 min readJun 6, 2022

--

Photo by Sam Moghadam Khamseh on Unsplash

Ever since the rise of APIs in the past decade every other application makes use of it as a primary way of communication between the client and the server or the recently developed microservices architecture.
Whenever you interact or use any web app it's very likely that the web app will be making calls to multiple REST APIs in the backend in order to return you the data or the service which you have requested for. But have you noticed that one doesn't need to visit separate links for each service for which you request but it is handled by a single URL endpoint which returns you the info which you are looking for.

Now the question arises how does the backend handle multiple API calls for different services? The simple answer is using a tool called API gateway. In this article, I will tell you what is an API gateway and how you can implement it in Google Cloud Platform (GCP) easily.

Contents

  1. What is an API gateway?
  2. Implementing API gateway in GCP
  3. Conclusion

1. What is an API gateway?

Let’s understand what is an API gateway in simple terms, Assume that you are a developer working on an application which consists of 3 services i.e weather ( which returns the current weather ), currency conversion (which can convert one currency value to another) and live score (which returns a score of a football match).
Now you have built these services which are independent of each other and want to expose your services as an API so that your clients/users can use them. When you try to deploy these APIs you will get a URL for each, with these URLs you & your users can access them. If the services you provide are fewer which in our case is 3 then it's ok to have a separate URL for each but if there are a lot of services then it becomes cumbersome and difficult to manage and keep track from both sides i.e users & developer.
This is where an API gateway comes into the picture as the name suggests “gateway” acts as a single entry point to all of your services as shown in the below image.

image source — www.wallarm.com

With an API gateway, you will get a single URL which will route the service request based on the name of that service.
For example, if you want to call any of the services then the format will be https://url-of-api-gateway/name-of-the-service. Likewise, if you want to call football score service then it will be https://url-of-api-gateway/live-score.

On top of this, you can also add features like authentication, authorization, load balancing, monitoring, fault tolerance, etc which will improve the APIs' performance and security.
One of the best parts of the API gateways is even if a service goes down or is updated in the backend the rest of the services will still be up and running.

And if you are wondering by now do we need to write our own API gateway? then the answer is no! there are lots of open-source gateways available to choose from for example Kong Gateway, Apache APISIX, Zuul, Gloo, etc. Different cloud platforms also provide their own implementation of gateways as well.
As you have some idea about API gateways now let's see them in action by using one provided by Google Cloud itself.

2. Implementing API gateway in GCP

Prerequisite: Basic knowledge of GCP and Gcloud SDK.

Before we proceed toward the implementation let's quickly go through our system architecture shown in the below image.

System architecture

The architecture that we are going to implement will be very simple. In short,
we will be using a GCP native API gateway which will call 3 serverless cloud functions which will act as a backend written in 3 different languages.
whenever you hit the gateway URL suffixed by the name of the service the gateway will route your request to the appropriate backend which will return back “hello world” string.

For the demonstration part, I will be using a sandbox environment of GCP.

Let's deep dive into the implementation! and follow me step by step.

Step 1: log in to your GCP console.

GCP console

Step 2: Enable required services.

In your GCP console open the cloud shell from the top-right icon and enter the below commands.

output after enabling services

Step 2.1: Clone my repository which contains all the codes you need.

cloning my repo

Step 3: Creating 3 Cloud Functions.

As a backend, we need 3 Cloud Functions so let's create them first.
And to do that make sure you are in the “gcp_api_gateway” folder and run the below commands.

after deploying the functions you will see the following in the shell.

after deploying cloud functions

To get more details about the deployed function run the following command.

You will get all the details of the functions after the execution of the above command.

Step 4: Creating an API.

Before you create a gateway you need first need to create and register the API in GCP. To do that run the below command.

replace the string in the quotes with your project id. After running the above command you should get the similar output shown below.

creating an API

Step 5: Creating routing rules for gateway configuration.

Before using the gateway we need to define some rules based on which the gateway can call the backed functions by using the names or paths of the Cloud Functions. These names and other details can be provided in a specification file named “openapi2.yaml” shown below.

You don’t need to create this specifically as it's already present in the repo. But all you need to do is replace the value of the key “address” with the URL of your deployed Cloud Functions.
To edit this you can also make use of cloud shell editor or any other text editor of your choice for example vim, vi, etc.

Step 5.1: Creating the gateway config.

As the openapi2.yaml file is ready, we will use it to create a configuration for the gateway. Run the below command to do so.

Replace the quotes with your project id & service account email respectively in the above command. After execution, you should see a similar output as below.

crating the config

Step 6: Creating the API gateway.

As everything is ready now let's create the API gateway and provide it with the name of the API created in the previous steps and the config file. Use the below command & replace the quotes with your project id.

After execution, you should see the similar output given below.

creating API gateway

Step 6.1: Testing our gateway.

We are almost done folks, Let's check if our gateway is performing as desired. Run the below commands in the shell.

You should now see “Hello World” from different backends written in 3 different languages as shown below.

testing the gateway

If you observe the above URLs, the gateway is calling the backend functions based on the names provided at the end of the URL and if any of these names match the names in the config file then that request will be routed to the specified Cloud Function URL which is present inside the config file.

Step 7: Adding a layer of security (bonus step).

As you have made it this far so here is a bonus step, where you can add a layer of security to our API by authenticating the request with an API key. If the API key is valid only then the request is routed to the backend function.

to get an API key in the search box above, type APIs and Services and click on it. You will land upon the below page.

getting API key

Click on the create credentials button and then select API key a pop window will open which contains the API key and copy it as we will need it going further.

Step 7.1: Updating the config file.

firstly let's enable our API service using the below command.

replace MANAGED_SERVICE_NAME with its value present inside the output of apis describe command above, then run the second command.

To use API key authentication for API calls we need a new config file containing the security details. Don’t worry this file is already present inside the repo, the file name is “secure-api.yaml”. Open the file & notice the changes & replace the address with your Cloud Function URLs (refer to step 5).

Step 8: Creating and updating the new config for the gateway.

We are now using the new config file which has the specification for key-based authentication. Now we need to create a new configuration & update the gateway so that it can start referring to the new config file.
Run the below commands. Replace the quotes with your project id and service account.

After executing you should see the output as shown below.

updating gateway config

Step 9: Testing new config for our gateway.

We are almost done the only thing left is to check if the new gateway config is working or not. Simply use the following commands one by one.

After execution of the first command if you get an error as below then congratulations! your API is now secured.

error without using the API key

To get the response from the backend Cloud Functions use the second command given above and replace the quotes with the API key which you created and saved in step 7. Run the command again now you should be able to see the output as shown in step 6.1.

3. Conclusion

To sum it up this is how you can simply make use of the API gateway provided by GCP. And also it's not necessary that the backend must always be Cloud Functions you can also use other services like App Engine & Cloud Run.
As this API gateway is a managed service so things like monitoring, scaling, performance and security are handled by GCP itself.

This was just a quick demo of how to get started with API gateways in GCP,
but you can also play around with it more to understand it better. If you want to dig deeper then here is the link for official documentation. And here is a link to my repo for all the code you will need.

In case you are looking to get certified in GCP then here is the link to my other article which will guide you through the preparation materials and the exam pattern so do check it out.
Finally, if you have any queries or doubts feel free to reach me on LinkedIn I will be happy to help you out. Hope this article helped you to learn and understand something new.

--

--

Prathmesh Patil

ML enthusiast, Data Science, Python developer, Google Cloud & Serverless. LinkedIn: https://www.linkedin.com/in/prathmesh