API Key Authentication with Google Cloud API Gateway and Cloud Run Posted on February 10, 2024February 15, 2024 By Justin Introduction Table of Contents Toggle IntroductionWARNINGBasic StepsPrerequisitesGoogle Cloud SetupEnable Needed Google Cloud ServicesConsole MethodCommand Line MethodCreate a Google Cloud Service AccountConsole MethodCommand Line MethodBackend API CreationCreate a simple Python-based APImain.pyrequirements.txtDockerfilestart.shDeploy Code as a Docker Container to Cloud RunTestingReenable AuthenticationGrant Service Account PermissionsAPI Gateway SetupCreate API Gateway APITesting Your APICloud Run URLAPI Gateway URLGET TestsPOST TestsConclusion I regularly use Google Cloud Run to host very simple APIs that, coupled with Google Composer (GCP’s hosted Airflow implementation), drive various data pipeline tasks. In most cases, I use service and user accounts created in Google’s Identity and Access Management (IAM) to handle authentication and authorization, but recently I had a use case where I needed to deploy an API endpoint that used API keys to handle that process. Thing is, I’m inherently lazy, and I didn’t want to try to write the code and processes necessary to handle management of keys in the application itself. And I’m only an accidental software developer, so I was worried that I might make a stupid mistake that made an already imperfect process even less secure. Thankfully, Google provides a service that can take care of it for you: API Gateway. In a nutshell, the API Gateway sits between the clients and your backend service (in my case, Cloud Run, but it could be a Cloud Function or App Engine instead) and, if configured properly, can (among other things) take over the authentication piece so lazy pseudo-developers like me don’t have to worry about it. Incoming requests provide a key to the API Gateway, and the API Gateway authenticates with the backend service with an IAM service account. Unfortunately, setting everything up can be a bit of a challenge the first time around. The documentation isn’t always clear (and misses a few essential steps) and some of the jargon can get a little, well, jargony. Hopefully, though, this step-by-step guide will help get you through a basic setup. WARNING This tutorial does involve the use of the Google Cloud Platform (GCP). While GCP does offer free options under a certain level of usage, there may be costs involved if you’ve already used your free quota, misconfigure some settings, and/or forget to shut down all these services later. Please remember to clean up after yourself so you don’t end up with a surprise bill. Pages: 1 2 3 4 5 6 7 8 9 10 11 12 Backend Stuff APICloud RunGCPPythonTutorial