This workshop is brought to you by DoiT. DoiT provides intelligent technology to simplify and automate public cloud use, alongside expert consultancy and unlimited technical support for digitally savvy companies. An award-winning strategic partner of Google Cloud and AWS, DoiT operates in more than 70 countries worldwide. For more information, visit doit.com.
To give you a sense of what to expect during the workshop and help you prepare and plan your time accordingly, the topics covered in this workshop include:
During the next two hours, we may not be able to complete all of the tasks, but try our best to get the most.
Feel free to ask questions π€ and seek help from the workshop mentor π§βπ« or others in the workshop π₯. Remember to have fun π and learn as much as possible π€.
Collaborative learning π€ can help ensure that you get the most out of the workshop π.
Itβs time to put on your running shoes and explore Cloud Run!. Youβll be sprinting through the guides and examples to gain a better understanding of how Cloud Run works and what it can do. By the end of this workshop, youβll be ready to start deploying your own applications to the platform.
πΌGoogle Cloud Run is a serverless platform that lets users run their applications in a fully managed environment without worrying about infrastructure. Cloud Run is built on top of Knative, an open-source project that provides middleware components for building modern, event-driven, cloud-native applications. Knative enables Cloud Run to offer features such as automatic scaling and traffic routing, making it easy for developers to focus on building their applications without worrying about the underlying infrastructure.

Google Cloud Free Trial offers free usage of Google Cloud services for a limited amount.
Before you can start using Google Cloud Run, you need to have a Google Cloud account and be logged in to the Google Cloud Console. You can follow the step-by-step instructions below to create a Google Cloud account and log in to the console, so that you are ready to get started.
It is often best to use a dedicated Google Cloud project for a workshop to avoid potential conflicts or issues. You can create a new project specifically for the workshop by following the instructions below.
Visit the Google Cloud Console
Click on the project selection button in the top-left corner of the Google Cloud Console page

π In the modal dialog that appears, click on βNew Projectβ in the top-right corner

π Give your project a unique name, for example: cloud-run-ws-[CUSTOM_NAME].
If you are using a personal GMail account, choose No Organization as the container for this project.

In this task, you visited the Google Cloud Console and created a new project with a unique name.
In this task, you will learn how to open the Google Cloud Shell and use it to manage your Google Cloud project.
The
π» Open the Google Cloud Shell by clicking on the

Make sure the correct project is selected in the Cloud Shell. If the wrong project is selected, change the project using the dropdown menu on the top-navigation bar and open a new shell.

π To check your permissions, run the following command:
gcloud auth list
This will display a list of the accounts that are currently authenticated to the cloud shell, along with their associated roles and permissions. This can help you verify that you have the correct permissions to use Google Cloud Run.

π Confirm that the Cloud Shell knows about your project by running the following command. Make sure that you are signed in to your Google Cloud account and that you have selected the correct project in the Cloud Shell. You can check your project by running the gcloud config list project command.
gcloud config list project

If you need to change the project, you can use the following command:
gcloud config set project [PROJECT_ID]π Try out the gcloud info command. This command provides a lot of useful information about your Google Cloud project, your gcloud installation, and your environment. You can use this information to troubleshoot any issues that you may encounter during this workshop, and to verify that your Google Cloud project and your gcloud installation are working correctly.
gcloud infoπ To enable the Google Cloud Run API, run the following command:
gcloud services enable run.googleapis.com
This command will allow your project to use Cloud Run.
π To set the default region for Google Cloud Run, you can run the following command in the cloud shell:
gcloud config set run/region me-west1
This will set the default region for Google Cloud Run, so that all subsequent commands you run will use this region unless otherwise specified.
You can now proceed to the next task in the workshop.
gcloud auth list command and the available flags, you can use the gcloud CLI tool and run the gcloud auth list --help command. This will show you the usage and syntax of the command, as well as a list of all the available flags and options.
The
π To open the Cloud Shell editor, click on the

π To create a new file, click on the
πΎ You can then enter your code or text into the file and save it using the

Once you have created and saved your file, you can use the editor to modify it and save your changes. You can also use the editor to open and edit existing files in your project.
π To close the editor, click on the
You can also click on the
You can now proceed to the next task in the workshop.
During this workshop, spend some time exploring the Cloud Run documentation and reading through the guides and examples. This will help you to understand how Cloud Run works, and will give you the knowledge you need to start deploying your applications to the platform. During this workshop, we will be using the quickstart guides to deploy our application to Cloud Run. It includes a reference section that provides detailed descriptions of the Cloud Run API and other technical details.
To get started, you can visit the Cloud Run documentation page at:
β¦and ready to proceed to the next task in the workshop.!
Now that youβve explored the Cloud Run documentation, youβre ready to take on the next challenge in the workshop. Letβs go!
Now that you have set up your Google Cloud project and enabled the necessary APIs, itβs time to start deploying applications to Cloud Run.
In this section of the workshop, you will learn how to use Cloud Run to deploy and run your applications in a fully managed environment. You will learn how to build and package your applications, how to configure and manage your deployments, and how to get your applications up and running on Cloud Run.
By the end of this section, you should have a good understanding of how to use Cloud Run to deploy and manage your applications, and you will be ready to start building and deploying your own applications on the platform. Letβs get started!
In this task, weβll be exploring the Google Cloud Console, the primary interface for managing and interacting with Google Cloud resources. By familiarizing yourself with the console, youβll be better equipped to use it during the workshop.
π» To open the Cloud Run console, go to console.cloud.google.com/run or search for βCloud Runβ in the Google Cloud Console and click on it in the results.

π In the Cloud Run console, navigate to Take the Quickstart page.

π Scroll down and click on the Python link under the βBuild and deploy a web serviceβ. This will open the quick start page for the Python application project.

π‘ Use the Guide Me button to start an interactive workshop for deploying your first Python application.

π Follow the instructions, and when your application is deployed the web page will show the following message:

π Congratulations! Your βHello worldβ application is now deployed. Visit its webpage to see the amazing graphics!

Refresh the Cloud Run console to see your service in the list of available services.

You have successfully deployed your first Google Cloud Run service!
In this task, weβll be cleaning up deployed services in Cloud Run using the Google Cloud Console.
Visit the Cloud Run page in Google Cloud Console at https://console.cloud.google.com/run.

Check the box next to your service, and choose to delete it.

When deploying the Cloud Run service with the local deployment option of Cloud Code in the Cloud Shell Editor, several additional resources are created in your project. Letβs find them and clean them up as well.
Visit the Cloud Container Registry page at https://console.cloud.google.com/gcr/images

and delete the content of your service container repository

Visit the Cloud Storage service page at https://console.cloud.google.com/storage/browser And delete the bucket containing your application assets, along with its contents

In this section, youβll learn how to use the Cloud Shell command line to deploy applications to Cloud Run.
Deploy and run your applications in a fully managed environment. You will learn how to build and package your applications, how to configure and manage your deployments, and how to get your applications up and running on Cloud Run.
By the end of this section, you will be a pro at using the Cloud Shell command line to deploy and manage your applications on Cloud Run. Letβs get started! πͺ
In this task, you will use the command-line interface (CLI) to deploy your application to Cloud Run. This allows you to quickly and easily deploy your application without building and managing container images.
Open
Change to the directory that contains your project files. The previous steps already created the hello-world directory in your cloud shell folder.
cd ~/hello-world-1Enable the Google Cloud Artifact Registry service in your Google Cloud project. This service allows Cloud Run to access your project files and dependencies, and to build and deploy your application to Cloud Run.
gcloud services enable artifactregistry.googleapis.com \
--project [PROJECT_ID]Enable the Google Cloud Build service in your Google Cloud project. This service allows Cloud Run to build and deploy your application to Cloud Run, using the source files and dependencies that are stored in the Google Cloud Artifact Registry.
gcloud services enable cloudbuild.googleapis.com \
--project [PROJECT_ID]Deploy the service using the gcloud run deploy command:
You will need to specify the name of your Cloud Run service. This name must be unique within your Google Cloud project, and it will be used to identify your service in the Cloud Run console and in the gcloud command-line tool.
You will also need to specify the location of your project files. This can be a directory or a file, depending on the structure of your project.
Optionally, you can specify the memory and CPU limits for your service. This allows you to control the resources that your service uses, and to optimize the performance and cost of your service.
To allow service access via the public internet, add allow-unauthenticated to the deploy command. To avoid unauthenticated requests, use --no-allow-unauthenticated instead.
gcloud config set run/region me-west1
gcloud run deploy \
--memory=128Mi \
--cpu=1 \
--allow-unauthenticated \
--region me-west1 \
--source . \
[SERVICE_NAME]
π Note: The . argument at the end of the command denotes the current directory.

Congratulations! You have successfully deployed an application to Google Cloud Run using the CLI.
In this task, you will learn how to inspect the build job logs to see the details about where Cloud Build stores the source files, the image, and the output of the build process.
To list the Cloud Build jobs that are associated with your Google Cloud project, you can use the gcloud builds list command, like this:
gcloud builds list
The output will show you a list of all the Cloud Build jobs that are associated with your Google Cloud project. The list will include the ID, status, and source of each build job, and it will help you identify the build job that was used by Cloud Run to create a container from your source files.
To get detailed information about a specific Cloud Build job, you can use the gcloud builds describe command, like this:
gcloud builds describe \
[BUILD_ID]
In this example, you need to replace [BUILD_ID] with the ID of the Cloud Build job that you want to get information about.
π‘ You can use tab completion to quickly and easily specify the ID of the build job, by pressing the TAB key after typing the gcloud builds describe command, and then selecting the build job that you want to get information about.
This command will show you detailed information about the specified build job, including its status, its source, its logs, and its artifacts. You can use this information to learn more about the build process, and to understand how Cloud Run used Cloud Build to create a container from your source files.
To view the logs of a specific Cloud Build job, you can use the gcloud builds log command, like this:
gcloud builds log \
[BUILD_ID]
In this example, you need to replace [BUILD_ID] with the ID of the Cloud Build job that you want to view the logs for.
π‘ Again, you can use tab completion to quickly and easily specify the ID of the build job, by pressing the TAB key after typing the gcloud builds log command, and then selecting the build job that you want to view the logs for.
This command will show you the logs of the specified build job, and it will include information about the build steps, the source files, and the output of the build process. You can use these logs to troubleshoot any issues or errors that may have occurred during the build process, and to learn more about how Cloud Build created a container from your source files.
π Note: You can use the --format argument with the gcloud builds list and gcloud builds describe commands, to specify the format of the output, and to customize the information that is shown by these commands. More information about (--format in the gcloud command line tool documentation](https://cloud.google.com/sdk/gcloud/reference/topic/formats).
You can also use the --verbosity argument with the commands, to specify the level of detail that you want to see. For more information about this argument, and for other options and features of the gcloud builds command, you can refer to the gcloud command-line tool documentation.
You have successfully explored the Cloud Build job that was used by Cloud Run to create a container from the source files in your project. You have learned how to list, describe, and view the logs for Cloud Build jobs, and you have gained a deeper understanding of the build process, and how Cloud Run and Cloud Build work together to deploy your application to the cloud.
You can continue to use the gcloud builds command to list, describe, and view the logs for Cloud Build jobs, as needed. You can also use the gcloud run command to monitor and manage your Cloud Run services, and to explore other features and capabilities of Cloud Run.
gcloud builds command-line tool.
gcloud builds describe command-line tool
gcloud builds log command-line tool
In this task, you will learn how to deploy new versions of your Cloud Run service, and how to manage and roll back to previous revisions if necessary.
π Open the templates/index.html file and make a small change, such as adding a new paragraph or changing the background color.
π» Deploy a new revision using the gcloud run deploy command. This command will create a new revision of your service, based on the source code and configuration files in your project directory, including the updated templates/index.html file that you just modified.
gcloud run services list command to get the name of your service and the region where it is deployed, and specify the name of the new revision that you want to create. Here is an example:gcloud run services list
gcloud run deploy [SERVICE_NAME] \
--region [REGION_ID] \
--source . \
--revision-suffix [REVISION_SUFFIX] \
--no-traffic
In this example, you need to replace [SERVICE_NAME] with the name of your Cloud Run service, [REGION_ID] with the region where you want to deploy your service (e.g.Β me-west1), and [REVISION_SUFFIX] with the name of the new revision that you want to create (e.g.Β v2).
Expect to see this result when the deploy command returns:
Service [hello-world] revision [hello-world-v2] has been deployed and is serving 0 percent of traffic.π Use the gcloud run revisions list command to view the list of revisions that are currently deployed for your Cloud Run service. This command will show you the name, service, and URL of each revision that is currently deployed for your Cloud Run service.
gcloud run revisions list --service [SERVICE_NAME]
In this example, you need to replace [SERVICE_NAME] with the name of your Cloud Run service.
gcloud run services list command.π Use the gcloud run services update-traffic command to specify the traffic allocation for each revision. This command allows you to specify the percentage of traffic that should be sent to each revision.
gcloud run services update-traffic [SERVICE_NAME] \
--to-revisions [NEW_REVISION_NAME]=25,[OLD_REVISION_NAME]=75

In this example, you need to replace [SERVICE_NAME] with the name of your Cloud Run service, [NEW_REVISION_NAME] with the name of the new revision that you want to send 25% of the traffic to, and [OLD_REVISION_NAME] with the name of the previous revision that you want to send 75% of the traffic to.
Refresh the updated service page several times, and verify that about once in four refresh cycles you get the new revision and the rest is still served with the old revision.
βͺ To fully roll back to a previous revision of your Cloud Run service, you can use the gcloud run services update-traffic command to specify that 100% of the traffic should be sent to the previous revision, effectively fully rolling back your service to the previous revision.
gcloud run services update-traffic [SERVICE_NAME] \
--to-revisions [OLD_REVISION_NAME]=100
In this example, you need to replace [SERVICE_NAME] with the name of your Cloud Run service, and [OLD_REVISION_NAME] with the name of the previous revision that you want to roll back to.
π To verify that the rollback was successful, visit your serviceβs URL and check that it is running the previous revision
For more information about managing and rolling back revisions in Cloud Run, see the official documentation.
Bonus: Check Cloud Run service page on the Google Cloud Console and see the options there for updating traffic and revisions.
In this task, you learned how to deploy new revisions of your Cloud Run service, and how to manage and roll back to previous revisions if necessary. You can use these skills to deploy updates to your Cloud Run services and manage the different versions of your service. π
gcloud run services update-traffic command-line tool.
gcloud run services list command-line tool.
gcloud run revisions list command-line tool.
In this task, we will learn how to scale our applications in Cloud Run. Scaling refers to the process of increasing or decreasing the number of instances of a service in response to changes in traffic. This can help us ensure that our applications can handle varying levels of traffic and remain performant and reliable.
We will cover how to scale services manually using the Cloud Run command-line interface (CLI) and the Cloud Run console, as well as how to set up automatic scaling based on predefined criteria.
To scale the service, use the gcloud run services update command, followed by the name of your service and the --concurrency flag, which specifies the maximum number of instances to run. For example,
gcloud run services update \
--concurrency=5 \
[SERVICE_NAME]π Note that a new revision was created, verify by running gcloud run revisions list [SERVICE_NAME] Describe the new revision and compare it to the existing revision that is currently deployed.
gcloud run revisions list \
[SERVICE_NAME]
gcloud run revisions describe \
[REVISION_NAME]βοΈ By default, Cloud Run services are automatically scaled to handle incoming traffic. This means that when traffic increases, the number of instances of the service will automatically increase to handle the additional workload. Similarly, when traffic decreases, the number of instances will automatically decrease to save resources and costs.
To adjust the scaling behavior of your service, use the gcloud run services update command, followed by the name of your service and the --min-instances and --max-instances flags. These flags specify the minimum and maximum number of instances that your service should have at any given time. Note that these have additional $$$ monthly cost.
For example, to set the minimum and maximum number of instances to 2 and 10, respectively, you would run:
gcloud run services update \
--min-instances 2 \
--max-instances 10 \
[SERVICE_NAME]In this task, you learned how to scale Cloud Run services manually using the command-line interface and the Cloud Run console, as well as how to set up automatic scaling based on predefined criteria. This is an important skill, as it allows you to manage the performance and reliability of your applications in Cloud Run.
gcloud run services update command and the available flags, you can use the gcloud CLI tool and run the gcloud run services update --help command. This will show you the usage and syntax of the command, as well as a list of all the available flags and options.
In this task, you will learn how to remove the created resources from your Google Cloud project. It is useful if you want to clean up your project and avoid incurring any unnecessary costs or charges.
Even after you deleted the Cloud Run service, your project may include resources such as Cloud Build, Artifact Registry, Cloud Storage buckets with assets, Pub/Sub topics, IAM roles, and other types created during the process.
π» In the Google Cloud Shell, run the following command to list the deployed services:
gcloud run services list
π Note the region and service name of the service you want to delete.
π§Ή Run the following command to delete the service:
gcloud run services list \
--format='value(region,name)'
gcloud run services delete \
--region [REGION_NAME] \
[SERVICE_NAME]
Where [REGION_NAME] is the name of the region where your Cloud Run service is deployed, and [SERVICE_NAME] is the name of the service that you want to delete.
β Confirm the deletion by typing Y when prompted.

π Verify that the service has been deleted by running the gcloud run services list command again.
You can list the successfully completed builds, these cannot be removed, but these can show where the sources files and resulting images, and logs are stored.
gcloud builds list
gcloud builds describe \
[BUILD_ID]Use the gcloud artifacts repositories delete command to delete your source files from your Artifact Registry. This command will remove the source files from your Google Cloud project.
gcloud artifacts repositories list
gcloud artifacts repositories delete \
--location [LOCATION_ID] \
[REPOSITORY_ID]Use the gsutil rm -r command to remove your Cloud Storage buckets and their contents. This command will remove the buckets and all their contents from your Google Cloud project.
gsutil ls
gsutil ls -r -lh $(gsutil ls)
gsutil rm -r \
[BUCKET_URL]

When deploying Cloud Run source-style deployments, it is using the Artifacts service instead of the Containers server. But just to make sure, check the containers to see if any show up in the listing.
gcloud container images list
To delete these containers, you can use the gcloud container images delete command, followed by the name of the container.
gcloud container images delete gcr.io/[PROJECT_NAME]/hello-world-1

As a last resort, removing the whole project will also remove all of the resources located in that project.
In this task, you learned how to remove Cloud Run services, source files from your Artifact Registry, and Cloud Storage buckets from your Google Cloud project. This is an optional step, but it is useful for cleaning up your project and avoiding unnecessary costs or charges. πΌ
To learn more about the gcloud run services commands, you can use the gcloud CLI tool and run
gcloud run services -h
gcloud run services --help
gcloud run services list --help
gcloud run services delete --help
This will show you the usage and syntax of the command, as well as a list of all the available flags and options.
gcloud run services delete command-line tool.
gcloud artifacts repositories delete command-line tool.
gsutil rm -r command-line tool.
In this task, we will learn how to schedule jobs in Cloud Run. Scheduled jobs allow us to run a Cloud Run service on a regular basis, according to a schedule that we define. This can be useful for tasks such as data processing, backups, and other types of periodic work. We will cover how to schedule jobs using the Cloud Run command-line interface (CLI) and the Cloud Run console, as well as how to view and modify the schedule for a job.
Deploy a Cloud Run Service from an existing image
gcloud run deploy \
--image us-docker.pkg.dev/cloudrun/container/hello \
--no-allow-unauthenticated \
--region [REGION_NAME] \
[SERVICE_NAME]
cloudrun/container/hello image contains code that will print hello to the console upon receiving an http request, we will be able to see these in the logs for this service in the next steps.Enable the Cloud Schedule API
gcloud services enable \
cloudscheduler.googleapis.comIn order for Cloud Scheduler to send authenticated requests to Cloud Run, create a new service account:
gcloud iam service-accounts create \
--display-name "[DISPLAYED_SERVICE_ACCOUNT_NAME]" \
[SERVICE_ACCOUNT_NAME]
Describe the details for this service account (email, etc..)
gcloud iam service-accounts listBind the service account to Cloud Run, to enable it invocation of Cloud Run services
gcloud run services add-iam-policy-binding \
--role=roles/run.invoker \
--region [REGION_NAME] \
--member=serviceAccount:[SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com] \
[SERVICE_NAME]Create a Cloud Scheduler job to invoke the Cloud Run service:
gcloud scheduler jobs create http \
--schedule "1 * * * *" \
--http-method=GET \
--uri=[SERVICE_URL] \
--oidc-service-account-email=[SERVICE_ACCOUNT_EMAIL] \
--oidc-token-audience=[SERVICE_URL] \
--location [REGION_NAME - us-central1 (not avail in me-west1)] \
[JOB_NAME]
List the scheduler jobs:
gcloud scheduler jobs list \
--location [REGION_NAME / us-central1]View the logs for your Cloud Run service
Install the Logs Streaming addon for gcloud:
sudo apt-get install google-cloud-sdk-log-streaming -y
View the logs for your service, stop tail using Ctrl-C
π Per the configuration above, Cloud Scheduler only sends a request once per minute, wait at least a minute to see output.
gcloud beta run services logs tail \
--region [REGION_NAME] \
[SERVICE_NAME]
You can also manually trigger the job in Cloud Scheduler with the command:
gcloud scheduler jobs run \
--location [REGION_NAME / us-central1] \
[JOB_NAME]
You can also use curl to call your service, which will generate a 403 Forbidden error as intended.

In previous sections we covered required commands for cleanup of resources. In this section, in addition to cleaning up the Cloud Run service it is also recommended to remove the IAM Service Account and Cloud Scheduler job.
Remove Cloud Scheduler Job
gcloud scheduler jobs list \
--location [REGION_NAME / us-central1]
gcloud scheduler jobs delete \
--location [REGION_NAME / us-central1] \
[JOB_NAME]Removing the IAM Service Account:
gcloud iam service-accounts list
List the existing policy allowing the Service Account to invoke this service
gcloud run services get-iam-policy \
--region [REGION_NAME] \
[SERVICE_NAME]
Remove the role binding from the Cloud Run Service
gcloud run services remove-iam-policy-binding \
--region [REGION_NAME] \
--member=serviceAccount:[SERVICE_ACCOUNT_EMAIL] \
--role roles/run.invoker \
[SERVICE_NAME]
Delete the Service Account
gcloud iam service-accounts delete \
[SERVICE_ACCOUNT_EMAIL]Remove Cloud Run Service (you know how!)
In this task, you learned how to use Cloud Scheduler to schedule jobs in Cloud Run using the command-line interface.
Blog post: Build a chat server with Cloud Run
Google Cloud Run Samples GitHub Repository
Community maintained Google Cloud Run - FAQ
If this introductory workshop was not enough, you can practice your skills with even more in-depth and diverse workshops:
Workshop: Google Pic-a-Daily Serverless Workshop
Workshop: Building containers & moving from dev to production
Workshop: Google Serverless Workshop
Workshop: Securely deploy to Cloud Run
Workshop: Cross-service Authentication
Workshop: Cloud Run Ingress
Workshop: Django on Cloud Run
Workshop: Modernize applications using Cloud Build Packs on Cloud Run
Lab: Cloud Run on Anthos
Course: App development with Cloud Run
You are now a Cloud Run expert! The world anxiously awaits your next big thing. Good luck!
The https://deploy.cloud.run button!
Mounting secrets in Cloud Run Services
Building your own containers in cloud Shell and pushing them to GCR
gcloud auth configure-docker
gcloud components install docker-credential-gcrCloud Run limits β Memory (32G) / Time (60m) / β¦ ?
πIn this task, we will learn how to integrate our Cloud Run services with databases and APIs. This can be useful for building applications that need to store and retrieve data, or communicate with other services. We will use a free-tier API that is available in Google Cloud as our target for integration, and we will cover the necessary steps and commands to set up and test the integration."
π§βπΌSteps
For this example, we will use the Cloud Natural Language API, which is a free-tier API in Google Cloud. To enable the API, run the following command:
gcloud services enable language.googleapis.comOnce you have enabled the Natural Language API, you can use the gcloud alpha run command to grant the Cloud Run internal Service Account access to the API. This will allow your Cloud Run service to access the API without the need for an API key.
gcloud alpha run services update [SERVICE_NAME] \
--add-service-account [PROJECT_NUMBER]@cloudservices.gserviceaccount.comNext, ensure that your Cloud Run service has the necessary dependencies and configuration to access the API. Update the Flask server dependencies by using the pip freeze command to generate a new requirements.txt file that includes the google-cloud-language library. To do this, run the following commands:
pip install google-cloud-language
pip freeze > requirements.txtWith the Natural Language API enabled and the Cloud Run internal Service Account granted access, you can update our simple Python Flask web application to use the Natural Language API to process requests. Update the Flask server route that you want to use the API (e.g.Β /) to call the API using the google-cloud-language library. For example, to analyze the sentiment of a piece of text using the API, you can use the following code in your Flask route:
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/')
def analyze_text():
# Extract the query string from the request
text = request.args.get('text')
# Create a client for the Natural Language API
client = language.LanguageServiceClient()
# Set the type of analysis to perform (sentiment analysis)
type_ = enums.Document.Type.PLAIN_TEXT
# Set the language of the text to analyze
language = "en"
# Create a document object with the text to analyze
document = types.Document(
content=text,
type=type_,
language=language
)
# Perform sentiment analysis on the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
# Return the sentiment score and magnitude to the user's browser
return "Sentiment score: {}\nSentiment magnitude: {}".format(
sentiment.score,
sentiment.magnitude
)
if __name__ == '__main__':
app.run()
With this Python Flask web application, you can deploy your Cloud Run service and make requests to it with a query string. The service will use the Natural Language API to analyze the query string and return the sentiment score and magnitude to the userβs browser.
Finally, deploy the updated Flask server to Cloud Run using the gcloud run deploy command. This will make the updated server available to users, allowing them to access the API through the Flask server. For example, to deploy the updated server, you can run the following command:
gcloud run deploy [SERVICE_NAME] \
--image gcr.io/my-project/my-server:latest \
--requirements requirements.txtAfter the service is deployed, you can test it by sending a request to the serviceβs URL. The URL can be found in the output of the gcloud run deploy command, or by using the gcloud run services describe command. For example, if the serviceβs URL is https://my-service-abcdefg-uc.a.run.app, you can test the service by sending a request to that URL, using the appropriate method for the service (e.g.Β GET for a HTTP GET request).
πIn this task, you learned how to integrate your Cloud Run service with databases and APIs. This can be useful for building applications that need to store and retrieve data, or communicate with other services. You learned how to enable and grant access to an API, how to add the necessary dependencies and configuration to your service, and how to use the API in your server code.