<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bhaarat Krishnan on Medium]]></title>
        <description><![CDATA[Stories by Bhaarat Krishnan on Medium]]></description>
        <link>https://medium.com/@bhaaratkrishnan?source=rss-2a45861119a3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O7IaEcJCcjzKgthva_6-fQ.jpeg</url>
            <title>Stories by Bhaarat Krishnan on Medium</title>
            <link>https://medium.com/@bhaaratkrishnan?source=rss-2a45861119a3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:57:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhaaratkrishnan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI Expense Tracker using Gemini 2.5 Flash, Google ADK, and Firestore]]></title>
            <link>https://medium.com/google-cloud/ai-expense-tracker-using-gemini-2-5-flash-google-adk-and-firestore-65bf88ad777f?source=rss-2a45861119a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/65bf88ad777f</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[google-adk]]></category>
            <dc:creator><![CDATA[Bhaarat Krishnan]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 04:23:57 GMT</pubDate>
            <atom:updated>2025-07-11T04:23:57.584Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>ExpenseTracker is an AI-powered web app that I built to help users effortlessly track expenses, manage monthly budgets, and gain insights into their spending habits through a conversational interface powered by Gemini AI, Google ADK, and Google Firestore.</p><h3>Tech Stack</h3><ul><li><strong>Google ADK:</strong> Google ADK is an open-source framework for building and deploying collaborative AI agents.</li><li><strong>ADK Web UI:</strong> The ADK Web UI provides a browser-based interface to interact with and debug your AI agents built with the Google ADK.</li><li><strong>Google Firestore:</strong> A scalable, serverless NoSQL database for storing user expenses and budgets.</li><li><strong>Gemini Flash 2.5:</strong> An agentic language model for natural language understanding and reasoning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CTjJT5RUXm7Hc3k8.gif" /></figure><h3>Setup</h3><h4>Create a new Google Cloud Project:</h4><p>Sign in or sign up for the Google Cloud Console and create a new project. Store the project ID for further use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*svaBBCNd3Qo4gv9h.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*dzCPbhKXkbAzJAO7.png" /></figure><p>Start the Google Cloud Shell, a remote shell environment in the cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*PUSHQjy2Y4Gil8gW.png" /></figure><p>Create Environment variables for REGION and PROJECT_ID.</p><pre>export PROJECT_ID=&lt;your project id&gt;</pre><pre>export REGION=us-east1</pre><p>Enabling APIs.</p><pre>gcloud services enable artifactregistry.googleapis.com \<br>cloudbuild.googleapis.com \<br>run.googleapis.com \<br>firestore.googleapis.com </pre><h4>Create a Firestore Database</h4><p>The documentation has more complete <a href="https://cloud.google.com/firestore/docs/create-database-server-client-library#create_a_in_native_mode_database">steps</a> to set up a Firestore instance. At a high level, to start, I will follow these steps:</p><ol><li>Go to the <a href="https://console.cloud.google.com/firestore">Firestore Viewer</a> and from the Select a database service screen, choose Firestore in Native mode</li><li>Select a location for your Firestore (Make sure to choose us-central1 and follow this wherever you choose region/location throughout this codelab)</li><li>In the security rules, select the “OPEN” so Security Rules so that the data is accessible.</li><li>Click Create Database (if this is the first time, leave it as “(default)” database)</li></ol><p>When you create a Firestore project, it also enables the API in the Cloud API Manager.</p><p>Once it’s set up, you should see the Firestore Database, Collection, and Document view in Native mode as seen in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wkaLQAk5tcg97z2J.png" /></figure><h4>Create a GCP Service Account</h4><p>A service account is a Google Cloud identity used by applications and services to access Google Cloud resources programmatically.</p><p>Create a new service account using this command. (Use the same terminal opened in the previous section)</p><pre>gcloud iam service-accounts create expense-tracker-sacc</pre><p>To provide access to your project and resources, grant a role to the service account.</p><pre>gcloud projects add-iam-policy-binding ${PROJECT_ID} --member=&quot;serviceAccount:expense-tracker-sacc@${PROJECT_ID}.iam.gserviceaccount.com&quot; --role=roles/datastore.owner</pre><h4>Get GEMINI API Key</h4><p>Google AI Studio is a web-based platform for prototyping and experimenting with Google’s generative AI models.</p><ol><li>Visit <a href="https://aistudio.google.com/">aistudio.google.com</a> and sign in using the same Google Account associated with your Google Cloud Console project.</li><li>In the top navigation bar, click <strong>“Get API Key”</strong> to access the API key management page.</li><li>Click <strong>“Create API Key”</strong>, then select the Google Cloud project you created earlier. Your new API key will be generated.</li><li><strong>Save this API key</strong> securely — you’ll need it to run and deploy the application.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*IvrammmyPrUVcynj.gif" /></figure><p>Great, we’re all set! Now, let’s dive into building the Agentic system and explore how it interacts with our databases.</p><h3>Why Firestore?</h3><p>Let’s see why we chose Firestore as our primary database.</p><p>Firestore is a serverless, real-time NoSQL database that perfectly fits ExpenseTracker’s AI-driven, chat-based workflow. It offers:</p><ul><li><strong>Flexible Schema</strong>: Easily stores structured data like expenses and budgets.</li><li><strong>Tight Integration</strong>: Works seamlessly with Google Cloud and Gemini APIs.</li><li><strong>Secure &amp; Scalable</strong>: Granular access rules and built-in scalability for growth.</li><li><strong>Event Triggers</strong>: Pairs well with Cloud Functions for reactive flows like alerts or summaries.</li></ul><h3>Agentic System Building</h3><p>Agentic systems shift from traditional software to intelligent, autonomous modules that interpret data, make decisions, and act independently. The Expense Agent uses AI to simplify adding and categorizing expenses with natural language and image processing.</p><h4>Features of the Expense Agent</h4><p>Our Expense Agent enhances the typical expense tracking workflow by handling unstructured inputs — text and images — with minimal user effort.</p><ul><li><strong>Smart Text Parsing</strong>: Users can type entries like <em>“Paid ₹500 for Zomato yesterday”</em>, and the agent extracts the amount, vendor, category, and date automatically.</li><li><strong>Image-Based Entry</strong>: Upload a receipt, and the agent, using Gemini multimodal APIs, analyzes it to extract key data like total amount, vendor name, and purchase date.</li><li><strong>Persistence:</strong> The Agent stores the extracted expense data in the Firestore database using the available tools.</li></ul><h4>How do Agents use Tools?</h4><p>Agents can’t directly access databases, APIs, or websites. So we give them <strong>tools,</strong> aka functions, that do those actions (like search, fetch data, update records). The agent “calls” these tools when needed.</p><h4>Example Interactions</h4><ul><li>Add ₹500 for groceries yesterday.</li><li>Set my monthly budget to ₹10,000”.</li><li>Show me my expenses for travel this month.</li></ul><h3>Deploy the Application</h3><p>Clone the repository and go to the directory.</p><pre>git clone https://github.com/bhaaratkrishnan/expense-tracker-gcp.git<br>cd expense-tracker-gcp</pre><p>Open Google Cloud Editor and replace GEMINI_API_KEY in the Dockerfile with your API KEY.</p><p>If the database name for the Firestore is not (default), mention it as an FIRESTORE_DB environment variable in the</p><p>Docker file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*uwbsJqSqL2uMQnZS.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*hDc2IcA_sFdvp8XHPnDr0Q.png" /></figure><p>Deploy the application to Cloud Run using this command:</p><pre>gcloud run deploy expense-tracker-gcp --source=. --port=8000 --allow-unauthenticated --service-account=expense-tracker-sacc@${PROJECT_ID}.iam.gserviceaccount.com --project=${PROJECT_ID} --region=us-east1</pre><p>Yaay !! <strong>Expense Tracker </strong>is up and running.</p><p>Expense Tracker is designed to simplify personal finance management and add a touch of fun. Give it a try and let Gemini models make your financial life easier and more enjoyable!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65bf88ad777f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/ai-expense-tracker-using-gemini-2-5-flash-google-adk-and-firestore-65bf88ad777f">AI Expense Tracker using Gemini 2.5 Flash, Google ADK, and Firestore</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Cloud Vertex AI and Svelte Kit: Vertex Summarizer]]></title>
            <link>https://medium.com/google-cloud/google-cloud-vertex-ai-and-svelte-kit-vertex-summarizer-5db792d0d80e?source=rss-2a45861119a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5db792d0d80e</guid>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Bhaarat Krishnan]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 02:35:41 GMT</pubDate>
            <atom:updated>2023-10-10T04:41:24.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>Vertex Summarizer is a web app that I created to allow users to summarize articles, text, and other forms of content using Google Cloud Vertex AI.</p><h4>Tech Stack</h4><ul><li>Svelte Kit: A web application framework that builds on Svelte.</li><li>Vertex AI PaLM 2 API: A large language model (LLM) API that provides access to Google AI’s PaLM 2 model.</li><li>Cloud Functions: A serverless platform to run functions without having to manage servers.</li><li>Cloud Run: A serverless platform to run containerized applications.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GfaMmSsqZm34Fhwz_6vKg.gif" /></figure><h3>Setup</h3><h4>Create new Google Cloud Project:</h4><p>Sign in or sign up to Google Cloud Console. Store the project ID for further use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*FPEvZTALuZHEiJGe.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*74CQ5qN5HGo9BmkO.png" /></figure><p>Start the Google Cloud Shell, a remote shell environment in cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*wJT3fVEwNtR8pSee.png" /></figure><p>Create Environment variables for REGION and PROJECT_ID.</p><pre>export PROJECT_ID=&lt;your project id&gt;</pre><pre>export REGION=asia-south1</pre><p>Enabling APIs</p><pre>gcloud services enable cloudbuild.googleapis.com \<br>run.googleapis.com \<br>cloudfunctions.googleapis.com \<br>aiplatform.googleapis.com</pre><h3>Vertex AI Cloud Function</h3><h4>Creating a new Service Account</h4><p>Create a new service account. (use the same terminal opened in previous section)</p><pre>gcloud iam service-accounts create vertex-service-acc</pre><p>To provide access to your project and your resources, grant a role to the service account.</p><pre>gcloud projects add-iam-policy-binding ${PROJECT_ID} --member=&quot;serviceAccount:vertex-service-acc@${PROJECT_ID}.iam.gserviceaccount.com&quot; --role=roles/ml.developer</pre><p>Grant your Google Account a role that lets you use the service account’s roles and attach the service account to other resources.</p><p>Replace USER_EMAIL with your Google Account Email ID.</p><pre>gcloud iam service-accounts add-iam-policy-binding vertex-service-acc@${PROJECT_ID}.iam.gserviceaccount.com --member=&quot;user:USER_EMAIL&quot; --role=roles/iam.serviceAccountUser</pre><h4>Creating Cloud Functions</h4><p>A Python Function is used to access the summarize text using PaLM API.</p><p>The PaLM 2 for text is ideal for tasks that can be completed with one API response, without the need for continuous conversation.</p><p>Create a new directory using cloud shell and navigate to it. (use the same terminal opened in previous section)</p><pre>mkdir vertex-ai-functions</pre><pre>cd vertex-ai-functions</pre><p>Create a main.py file for writing cloud function and requirements.txt file for storing dependencies.</p><pre>touch main.py requirements.txt</pre><p>This Python file defines a simple HTTP Cloud Function that uses a Vertex AI Text Generation Model to generate short summaries of text inputs. The function takes a text input as a parameter and returns a short summary of the input. The function uses a variety of parameters to control the generation process, such as the creativity, diversity, and fluency of the generated text. The HTTP Cloud Function accepts a request object and returns the model’s summary as the response.</p><p>Open Google Cloud Editor and replace main.py contents with this code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*d71cJlZhNUNAMxMPRgSjZg.png" /></figure><pre>#main.py<br>import functions_framework<br>import vertexai<br>from vertexai.preview.language_models import TextGenerationModel<br>import json<br><br># Replace with your project ID !!!<br>PROJECT_ID = &quot;&quot;<br><br>def interview(text:str):<br>    parameters = {<br>        &quot;temperature&quot;: 0.2,<br>        &quot;max_output_tokens&quot;: 256,   <br>        &quot;top_p&quot;: .8,                <br>        &quot;top_k&quot;: 40,                 <br>    }<br>    vertexai.init(project=PROJECT_ID)<br>    model = TextGenerationModel.from_pretrained(&quot;text-bison@001&quot;)<br>    response = model.predict(<br>        f&quot;Make a short summary : {text}&quot;,<br>        **parameters,<br>    )<br>    print(f&quot;Response from Model: {response.text}&quot;)<br>    return response.text<br><br>@functions_framework.http<br>def hello_vertex(request):<br>    parsed_data = (str(request.data)).replace(&#39;&quot;&#39;,&quot;&quot;).replace(&quot;&#39;&quot;,&quot;&quot;).replace(&quot;,&quot;,&quot;&quot;).replace(&quot;\n&quot;,&quot;&quot;)<br>    model_response =  interview(parsed_data)<br>    headers = {&quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;}<br>    return (model_response, 200, headers)<br><br><br><br></pre><p>Overall, this file provides a concise way to generate short summaries of text inputs using Vertex AI.</p><p>The requirements.txt file have package dependencies:</p><ul><li>functions-framework==3.*: Ensures that the function uses the latest features and bug fixes of the Functions Framework.</li><li>google-cloud-aiplatform: Required to use the Vertex AI Text Generation Model.</li></ul><p>Add this to requirements.txt file.</p><pre>functions-framework==3.*<br>google-cloud-aiplatform</pre><p>Deploy to Google Cloud Functions.</p><pre>gcloud functions deploy vertex-ai-function \<br>--gen2 \<br>--runtime=python311 \<br>--region=${REGION} \<br>--source=. \<br>--entry-point=hello_vertex \<br>--trigger-http \<br>--allow-unauthenticated \<br>--max-instances=30</pre><p>Use the search bar and go to Cloud Functions Panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*hxJmh4tZQv4PI6XmbA1Xlg.png" /></figure><p>The function panel will contain the vertex-ai-function cloud function and the public URL will be given in the function page. We use this to connect our Frontend and Vertex AI API. Store this URL.</p><h3>Vertex Summarizer Web App</h3><p>The Vertex Summarizer provides a frontend interface to interact with our Vertex AI API through Google Cloud Functions.</p><h4>Clone Repository and Setup Dockerfile</h4><p>Go to root directory and clone the git repository.</p><pre>cd ~/</pre><pre>git clone https://github.com/bhaaratkrishnan/vertex-summarizer-svelte.git</pre><pre>cd  vertex-summarizer-svelte</pre><p>To run this application, you need to add the PUBLIC_FUNCTION_URL environment variable in Dockerfile. This URL is the Cloud Function URL created and stored in previous section.</p><p>Open Cloud Editor and edit contents of Dockerfile. Replace the PUBLIC_FUNCTION_URL variable with your Cloud Function URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*S_1OuNSQj9ruS9cX_C9Krg.jpeg" /></figure><h4>Deploy Frontend to Cloud Run</h4><p>We will be using Google Artifact Registry to build and store our Docker Images. Cloud Run is used to deploy the containers in Serverless Architecture.</p><p>Create an Artifact Registry Repository. Open the Cloud Shell (use the same terminal opened in previous section).</p><pre>gcloud artifacts repositories create vertex-repo --repository-format=docker --location=${REGION} </pre><p>Create an environment variable for Artifact Registry repository URL.</p><pre>export DOCKER_URL=${REGION}-docker.pkg.dev/${PROJECT_ID}/vertex-repo/vertex-summarizer-image</pre><p>Build the docker container and tag it with Artifact Registry Repository location. Tagging the Docker image with a repository name configures the docker push command to push the image to a specific location.</p><pre>docker build . -t ${DOCKER_URL}</pre><p>Push the image to Artifact Registry.</p><pre>docker push ${DOCKER_URL}</pre><p>Deploy docker container to Cloud Run.</p><pre>gcloud run deploy vertex-summarizer --allow-unauthenticated --platform=managed --region=${REGION} --image=${DOCKER_URL}</pre><p>Yaay !! <strong>Vertex Summarizer</strong> is up and running. The URL will be shown in Cloud Shell, so Explore and Enjoy Vertex AI🤖.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5db792d0d80e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/google-cloud-vertex-ai-and-svelte-kit-vertex-summarizer-5db792d0d80e">Google Cloud Vertex AI and Svelte Kit: Vertex Summarizer</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bookshelf Explorer: Serverless Web API]]></title>
            <link>https://medium.com/google-cloud/implementation-of-serverless-web-apis-codelab-56f2068c56c?source=rss-2a45861119a3------2</link>
            <guid isPermaLink="false">https://medium.com/p/56f2068c56c</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-functions]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <dc:creator><![CDATA[Bhaarat Krishnan]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 10:36:28 GMT</pubDate>
            <atom:updated>2023-08-17T02:41:46.525Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog and implementation are a derivation of the <a href="https://codelabs.developers.google.com/codelabs/serverless-web-apis#0">Serverless Web APIs Codelab</a> by <a href="https://glaforge.medium.com/">Guillaume Laforge</a>, with some forks in the flow approved by the author.</p><h3>Overview</h3><p>The goal of this implementation is to learn about serverless services offered by Google.</p><ol><li><strong>Cloud Functions </strong>to deploy small units of business logic in the shape of functions, that react to various events.</li><li><strong>Cloud Run t</strong>o deploy and scale containers, that can contain any language, runtime or library.</li></ol><h4>What are we building?</h4><ol><li>This workshop guides in building a bookshelf explorer with Google Cloud Services.</li><li>Cloud Function is used for data import, a Cloud Run container for a REST API with a Web user interface.</li></ol><figure><img alt="Bookshelf explorer web user interface" src="https://cdn-images-1.medium.com/max/856/1*Fl23Yu8g8JWrRkRGDmi7Ow.png" /></figure><h3>What is Serverless?</h3><p>Serverless is a cloud computing paradigm that abstracts away the complexity of server management and infrastructure provisioning.</p><h3>Setup and Requirements</h3><ol><li>Sign up or Sign into your Google Cloud account and create a new project. After creating your project, note your project ID to further use.</li><li>Start your cloud shell which creates a command line environment in Google Cloud.</li></ol><h4>Enabling APIs</h4><p>Google Cloud APIs are programmatic interfaces that allow users to access Google Cloud Platform services. We can enable Google Cloud APIs required for our project using this command:</p><pre>gcloud services enable \<br>cloudbuild.googleapis.com \<br>artifactregistry.googleapis.com \<br>cloudfunctions.googleapis.com \<br>firestore.googleapis.com \<br>run.googleapis.com</pre><h4>Creating Environment Variables</h4><p>We will have two environment variables. The first will be region and second is project id.</p><pre>export REGION=asia-south1<br>export PROJECT_ID={your_project_id}</pre><h4>Creating Firestore Database</h4><p>Firestore is a flexible and scalable NoSQL cloud database provided by Google Cloud. It’s designed to store and manage data in a way that’s easy to access and efficient to scale. We will use firestore database to store our books data.</p><pre>gcloud firestore databases create --location=${REGION}</pre><h4>Cloning Repository</h4><pre>git clone https://github.com/glaforge/serverless-web-apis </pre><p>The repository contains the source code for application written in <em>node.js.</em></p><p>The directory structure:</p><ol><li>data: Holds a JSON sample of 100 books.</li><li>functions-import: Contains a function for importing data via an endpoint.</li><li>run-crud: Contains the Web API exposing Firestore-stored books.</li><li>appengine-frontend: Offers a basic read-only interface for displaying book lists.</li></ol><h4>Sample Books Data</h4><p>The data folder contains the data.json file which is list of books objects.</p><pre>[<br>  {<br>    &quot;isbn&quot;: &quot;9780435272463&quot;,<br>    &quot;author&quot;: &quot;Chinua Achebe&quot;,<br>    &quot;language&quot;: &quot;English&quot;,<br>    &quot;pages&quot;: 209,<br>    &quot;title&quot;: &quot;Things Fall Apart&quot;,<br>    &quot;year&quot;: 1958<br>  },<br>  {<br>    &quot;isbn&quot;: &quot;9781414251196&quot;,<br>    &quot;author&quot;: &quot;Hans Christian Andersen&quot;,<br>    &quot;language&quot;: &quot;Danish&quot;,<br>    &quot;pages&quot;: 784,<br>    &quot;title&quot;: &quot;Fairy tales&quot;,<br>    &quot;year&quot;: 1836<br>  },<br>  ...<br>]</pre><ol><li>isbn: The 13-digit code for identifying the book.</li><li>author: The name of author of the book.</li><li>language: Language in which the book is written.</li><li>pages: Total pages of the book.</li><li>title: Title of the book.</li><li>year: Published year of the book.</li></ol><h3>Deploying Cloud Functions</h3><p>We will see a few questions here to understand the usage of Google Cloud Functions.</p><h4>What use case does Google Cloud Functions have here?</h4><p>We will use these Google Cloud Function to create and insert books into our database.</p><h4>So why google cloud functions ? How are they different from our usual functions?</h4><p>Great Question! Let us see this simple JS function which takes in a list of books as function parameters and inserts it in firestore database.</p><pre>...<br>async function insertBooks(books) {<br>  const writeBatch = firestore.batch();<br>  <br>  for (const book of books) {<br>    const doc = bookStore.doc(book.isbn);<br>    writeBatch.set(doc, {<br>      title: book.title,<br>      author: book.author,<br>      language: book.language,<br>      pages: book.pages,<br>      year: book.year,<br>      updated: Firestore.Timestamp.now()<br>    });<br>  }<br><br>  try {<br>    await writeBatch.commit();<br>    console.log(&quot;Saved books in Firestore&quot;);<br>    return &quot;OK&quot;;<br>  } catch (e) {<br>    console.error(&quot;Error saving books:&quot;, e);<br>    throw new Error(&quot;Error saving books&quot;);<br>  }<br>}<br>...</pre><p>We have a great function that adds books to our database. How can we make it work seamlessly across different tech setups?</p><p>Google Cloud Functions are a good solution. They are event-driven, scalable, and serverless. They also work seamlessly with many Google services, including Firestore.</p><p>Let’s convert this function to a <strong>Google Cloud Function</strong> 🔥:</p><p>Search for <em>Cloud Functions</em> in Google Cloud Console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*-OCdKPtRaLGwNxFIDyGdCg.jpeg" /></figure><p>Click on create function button and you will be taken to this screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*CgJ5rovm4fpLY4RCofPD2w.jpeg" /></figure><p>Feel free to give your function name and make sure to enable allow unauthenticated invocations option in HTTP trigger. Click next button to land on inline editor to start creating our cloud functions.</p><p>Change the <strong>Entry point </strong>to “parseBooks”.</p><p>Replace the package.json contents:</p><pre>{<br>  &quot;dependencies&quot;: {<br>        &quot;@google-cloud/firestore&quot;: &quot;^4.9.9&quot;,<br>        &quot;@google-cloud/functions-framework&quot;: &quot;^3.1.0&quot;<br>    }<br>}</pre><p>Replace index.js contents with our function wrapped in Google Cloud Function Framework:</p><pre>const Firestore = require(&#39;@google-cloud/firestore&#39;);<br>const functions = require(&#39;@google-cloud/functions-framework&#39;);<br>const firestore = new Firestore();<br>const bookStore = firestore.collection(&#39;books&#39;);<br><br>functions.http(&#39;parseBooks&#39;, async (req, resp) =&gt; {<br>    if (req.method !== &quot;POST&quot;) {<br>        resp.status(405).send({error: &quot;Only method POST allowed&quot;});<br>        return;<br>    }<br>    if (req.headers[&#39;content-type&#39;] !== &quot;application/json&quot;) {<br>        resp.status(406).send({error: &quot;Only application/json accepted&quot;});<br>        return;<br>    }<br><br>    const books = req.body;<br>    // console.debug(books);<br><br>    const writeBatch = firestore.batch();<br><br>    for (const book of books) {<br>        const doc = bookStore.doc(book.isbn);<br>        writeBatch.set(doc, {<br>            title: book.title,<br>            author: book.author,<br>            language: book.language,<br>            pages: book.pages,<br>            year: book.year,<br>            updated: Firestore.Timestamp.now()<br>        });<br>    }<br><br>    try {<br>        await writeBatch.commit();<br>        console.log(&quot;Saved books in Firestore&quot;);<br>    } catch (e) {<br>        console.error(&quot;Error saving books:&quot;, e);<br>        resp.status(400).send({error: &quot;Error saving books&quot;});<br>        return;<br>    };<br><br>    resp.status(202).send({status: &quot;OK&quot;});<br>})</pre><p>Now click on deploy to start our function deployment and that’s it. We have our Amazing Google Cloud Function up and running.</p><p>We can test it by using Function URL and sending a POST request to it.</p><p>Open your cloud shell and go to <em>serverless-web-apis</em> directory and run this command.</p><pre>curl -d &quot;@./data/books.json&quot; \<br>       -H &quot;Content-Type: application/json&quot; \<br>       $YOUR_FUNCTION_URL</pre><p>We can check if the books have been uploaded to our database using GCP Console. Search for firestore and select one with <em>Data</em> as title and <em>firestore </em>as subtitle.</p><p>A books collection will be created with all our books inserted into the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*FuWUfnW9okWhFuROTwpdLg.png" /></figure><h3>Deploy Containers to Cloud Run</h3><p>Too many technical terms, right? Let’s break it down!</p><h4>Containers</h4><p>Containers are a way to package and run applications. They isolate the application from its environment, so it can be deployed and scaled easily. <strong>Docker</strong> is a popular container platform.</p><h4>Why Docker and Containers?</h4><p>Docker and containers make apps portable, scalable, and efficient. They streamline development, integrate with CI/CD, and are key to microservices, cloud, and modern deployment.</p><h4>What use case does Google Cloud Run have here?</h4><p>We crafted a Web API with express.js and node.js for book CRUD. We’ll deploy this API using Docker and containers. Google Cloud Run offers serverless deployment, scaling, and cost efficiency. Our Amazing Bookshelf is now globally accessible.</p><h4>Let’s get started🔥</h4><p>Open Google Cloud Shell and navigate to /serverless-web-apis/run-crud/ directory which contains Web API and <em>Dockerfile.</em></p><p>The package.json file contains the required dependencies for running our web API server:</p><ol><li><em>express.js</em> is a minimal and flexible Node.js web application framework.</li><li><em>firestore</em> is client SDK offered by Google Cloud to easily access our database.</li><li><em>cors </em>is a node.js package for providing a <a href="http://expressjs.com/">Express</a> middleware that can be used to enable CORS with various options.</li></ol><p>The index.js file is the entry point to our web API. It initializes the express server and listens to all requests on port 8080. We will focus on the implementation of GET and POST requests, but feel free to explore the source code for the PUT and DELETE methods as well.</p><p><strong>GET </strong>method retrieves books from our database. Implementation-wise, we’re listening to GET requests at /books path. The function fetches the initial 10 books, using query parameters to filter by author and language.</p><pre>app.get(&#39;/books&#39;, async (req, res) =&gt; {<br>    try {<br>        var query = new Firestore().collection(&#39;books&#39;);<br><br>        if (!!req.query.author) {<br>            console.log(`Filtering by author: ${req.query.author}`);<br>            query = query.where(&quot;author&quot;, &quot;==&quot;, req.query.author);<br>        }<br>        if (!!req.query.language) {<br>            console.log(`Filtering by language: ${req.query.language}`);<br>            query = query.where(&quot;language&quot;, &quot;==&quot;, req.query.language);<br>        }<br><br>        const page = parseInt(req.query.page) || 0;<br><br>        const snapshot = await query<br>            .orderBy(&#39;updated&#39;, &#39;desc&#39;)<br>            .limit(PAGE_SIZE)<br>            .offset(PAGE_SIZE * page)<br>            .get();<br><br>        const books = [];<br><br>        if (snapshot.empty) {<br>            console.log(&#39;No book found&#39;);<br>        } else {<br>            snapshot.forEach(doc =&gt; {<br>                const {title, author, pages, year, language, ...otherFields} = doc.data();<br>                const book = {isbn: doc.id, title, author, pages, year, language};<br>                books.push(book);<br>            });<br>        }<br><br>        var links = {};<br>        if (page &gt; 0) {<br>            const prevQuery = querystring.stringify({...req.query, page: page - 1});<br>            links.prev = `${req.path}${prevQuery != &#39;&#39; ? `?${prevQuery}` : &#39;&#39;}`;<br>        }<br>        if (snapshot.docs.length === PAGE_SIZE) {<br>            const nextQuery = querystring.stringify({...req.query, page: page + 1});<br>            links.next = `${req.path}${nextQuery != &#39;&#39; ? `?${nextQuery}` : &#39;&#39;}`;<br>        }<br>        if (Object.keys(links).length &gt; 0) {<br>            res.links(links);<br>        }<br><br>        res.status(200).send(books);<br>    } catch (e) {<br>        console.error(&#39;Failed to fetch books&#39;, e);<br>        res.status(400)<br>            .send({error: `Impossible to fetch books: ${e.message}`});<br>    }<br>});</pre><p><strong>POST Method</strong> is used to create books in the database. We will listen to POST requests in same path /books. The request body contains the book data in form of JSON with required attributes. The createBook function is then executed to write this data to our database.</p><pre>app.post(&#39;/books&#39;, async (req, res) =&gt; {<br>    const isbn = req.body.isbn;<br>    createBook(isbn, req, res);<br>});</pre><h4>Dockerfile</h4><p>A Dockerfile is a script defining steps to build a container image. It contains commands to create an application-ready environment.</p><p>Our <em>Dockerfile</em> looks like this:</p><pre>FROM node:20-slim<br>WORKDIR /usr/src/app<br>COPY package*.json ./<br>RUN npm install --only=production<br>COPY . ./<br>CMD [ &quot;node&quot;, &quot;index.js&quot; ]</pre><ol><li>FROM node:20-slim : Base image “node:20-slim” provides Node.js runtime and essentials.</li><li>WORKDIR /usr/src/app: Sets working directory inside the container to /usr/src/app.</li><li>COPY package*.json ./: Copies package.json to the container’s working directory.</li><li>RUN npm install --only=production: Executes “npm install” inside the container.</li><li>COPY . ./: Copies remaining source files to the container.</li><li>CMD [&quot;node&quot;, &quot;index.js&quot;]: Entry point to start the container, launching the web API using node index.js. Uses an array of strings as the command.</li></ol><p>Woah! that’s a lot of work. All we need to do now is to build the image, deploy it in Cloud Run and our web API will be up and running in Cloud Run.</p><h4>Build the Image</h4><p>Create a repository in Artifact Registry</p><pre>gcloud artifacts repositories create cv3-repo \ <br>--repository-format=docker \ <br>--location=${REGION}</pre><p>Build docker image locally with tag for artifact registry.</p><pre>docker build -t gcr.io/${PROJECT_ID}/cv3-repo/run-crud-api .</pre><p>Push this image to artifact registry.</p><pre>docker push gcr.io/${PROJECT_ID}/cv3-repo/run-crud-api</pre><h4>Deploy the image to Cloud Run</h4><pre>gcloud run deploy run-crud \<br>         --image=gcr.io/${PROJECT_ID}/cv3-repo/run-crud-api \<br>         --allow-unauthenticated \<br>         --region=${REGION} \<br>         --platform=managed</pre><p>It’s done guys! our web API container is deployed to Cloud Run, we can use the URL to access the API. Go to YOUR_API_URL/books in your browser. This uses the GET request to query the first 10 books in database.</p><pre>[<br>    {<br>        &quot;isbn&quot;: &quot;9782070369218&quot;,<br>        &quot;title&quot;: &quot;Memoirs of Hadrian&quot;,<br>        &quot;author&quot;: &quot;Marguerite Yourcenar&quot;,<br>        &quot;pages&quot;: 408,<br>        &quot;year&quot;: 1951,<br>        &quot;language&quot;: &quot;French&quot;<br>    },<br>    {<br>        &quot;isbn&quot;: &quot;9781585102259&quot;,<br>        &quot;title&quot;: &quot;The Aeneid&quot;,<br>        &quot;author&quot;: &quot;Virgil&quot;,<br>        &quot;pages&quot;: 442,<br>        &quot;year&quot;: -23,<br>        &quot;language&quot;: &quot;Classical Latin&quot;<br>    },<br>...<br>]</pre><p>We will try using queries to get top 10 books in french, go to YOUR_API_URL/books?language=French.</p><p>You would have received an Error.</p><pre>{<br>    &quot;error&quot;: &quot;Impossible to fetch books: 9 FAILED_PRECONDITION: <br>The query requires an index. You can create it here: ${URL_TO_CREATE_INDEX}&quot;<br>}</pre><p>The query requires an index! Why?</p><p>Firestore needs indexes for fast data querying. Without them, searches become sluggish as the entire database is scanned. Indexes create a data map, enabling Firestore to quickly locate relevant documents.</p><p>To create an index, visit the URL, log in, grant “language” field index permission, click “Create,” and the index will be ready in 2–10 minutes.</p><p>To create an index, visit the URL, log in, grant “language” field index permission, click “Create,” and the index will be ready in 2–10 minutes.</p><p>After index creation we will try again to get top 10 French books from our database. YOUR_API_URL/books?language=French</p><pre>[<br>    {<br>        &quot;isbn&quot;: &quot;9782070369218&quot;,<br>        &quot;title&quot;: &quot;Memoirs of Hadrian&quot;,<br>        &quot;author&quot;: &quot;Marguerite Yourcenar&quot;,<br>        &quot;pages&quot;: 408,<br>        &quot;year&quot;: 1951,<br>        &quot;language&quot;: &quot;French&quot;<br>    },<br>    {<br>        &quot;isbn&quot;: &quot;9788437616926&quot;,<br>        &quot;title&quot;: &quot;Gargantua and Pantagruel&quot;,<br>        &quot;author&quot;: &quot;François Rabelais&quot;,<br>        &quot;pages&quot;: 623,<br>        &quot;year&quot;: 1533,<br>        &quot;language&quot;: &quot;French&quot;<br>    },<br>...<br>]</pre><p>Attempt querying by the author’s name, and you’ll encounter the same error. Proceed to the provided URL to create an index, and then retry the author-based query. Feel free to test all the HTTP methods.</p><h3>Deploying Books Frontend to Cloud Run (Optional)</h3><p>I think, at this point we all know Cloud Run, Docker, Containers, Artifact Registry, so we will make it quick. Navigate to serverless-web-apis/appengine-frontend directory.</p><p>First, create a Dockerfile</p><pre>touch Dockerfile</pre><p>Now go to Google Inline Editor and paste the following configuration in Dockerfile</p><pre>FROM node:20-slim<br>WORKDIR /usr/src/app<br>COPY package*.json ./<br>RUN npm install --only=production<br>COPY . ./<br>ENV RUN_CRUD_SERVICE_URL=${YOUR_WEB_API_URL}<br>CMD [ &quot;node&quot;, &quot;index.js&quot; ]</pre><p>Build the image locally with artifact registry tag.</p><pre>docker build -t gcr.io/${PROJECT_ID}/cv3-repo/books-frontend .</pre><p>Push it to artifact registry.</p><pre>docker push gcr.io/${PROJECT_ID}/cv3-repo/books-frontend </pre><p>Deploy this image to Cloud Run.</p><pre>gcloud run deploy books-frontend \<br>         --image=gcr.io/${PROJECT_ID}/cv3-repo/books-frontend \<br>         --allow-unauthenticated \<br>         --region=${REGION} \<br>         --platform=managed</pre><p>Again Woah! but I think we did a lot faster this time. Now you go to this container URL to access the frontend.</p><h3>Summary</h3><p>We created a set of serverless services, thanks to Cloud Functions and Cloud Run, to expose various Web API endpoints and web frontend, to view all our books.</p><p>Services we have covered:</p><ol><li>Google Cloud Run</li><li>Google Cloud Functions</li><li>Google Cloud Firestore</li><li>Google Artifact Registry</li></ol><p>Through a seamless integration of these services, developers can build scalable, secure, and highly available APIs that adapt to varying workloads, all while enjoying the streamlined development and cost efficiency that serverless architectures bring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56f2068c56c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/implementation-of-serverless-web-apis-codelab-56f2068c56c">Bookshelf Explorer: Serverless Web API</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>