Welcome, Firebase enthusiasts!
Today, we’re venturing into the realm of serverless computing that can be integrated with AI using Python language to explore the wonders of cloud functions with Python, specifically with Firebase Cloud Functions. These functions offer a seamless way to execute code in response to various triggers, all without the hassle of managing servers.
But before we dive deep into serverless territory, let’s briefly compare this approach with another popular architectural pattern: microservices.
Serverless cloud functions and microservices are both architectural patterns used to build scalable and flexible applications. However, they differ in several key aspects:
1. Resource Management:
- Serverless Cloud Functions: With serverless functions, cloud providers handle infrastructure management, including server provisioning, scaling, and maintenance. Developers focus solely on writing code without worrying about underlying infrastructure.
- Microservices: Microservices require developers to manage their own infrastructure, including servers, containers, and orchestration tools like Kubernetes. While this offers more control over resources, it also adds complexity and overhead.
2. Scaling:
- Serverless Cloud Functions: Cloud functions automatically scale up or down based on demand. Providers allocate resources dynamically, ensuring optimal performance and cost efficiency.
- Microservices: Scaling microservices involves manual or automated management of resources. Developers must anticipate traffic patterns and adjust resource allocation accordingly, which can be challenging to implement and maintain at scale.
3. Cost:
- Serverless Cloud Functions: Serverless functions offer a pay-as-you-go pricing model, where you’re charged only for the resources used during execution. This can be cost-effective for sporadic workloads with unpredictable traffic.
- Microservices: Microservices require constant resource allocation, regardless of workload fluctuations. While this provides more predictable costs, it can lead to overprovisioning and wasted resources during periods of low activity.
4. Development and Deployment:
- Serverless Cloud Functions: Developing and deploying serverless functions is straightforward and requires minimal setup. Developers focus on writing code, and deployment is handled through simple CLI commands or CI/CD pipelines.
- Microservices: Developing and deploying microservices involves more upfront setup, including infrastructure provisioning, containerization, and service discovery. Managing dependencies and versioning across multiple services adds complexity to the development and deployment process.
Now that we’ve outlined the differences between serverless cloud functions and microservices, let’s delve into the specifics of building and deploying cloud functions with Python using Firebase Cloud Functions.
Without further ado, let’s get started by setting up our Firebase project.
Ensure you have Python installed on your system. If you haven’t already, install the Firebase CLI globally using npm:
npm install -g firebase-tools
Next, log in to your Google account and initialize a Firebase project in your desired directory. During the initialization process.
firebase login
firebase init functions
you’ll be prompted to choose either JavaScript or TypeScript as your default language. Select Python if prompted.
After that, you will be given this project structure to get started with!
Now, before we proceed to the code, do not forget to add Flask into the requirements.txt to integrate Flask into our Cloud Functions, at the time of writing I do recommend using version 2.1.2 for the supported version with Cloud Functions.
Then let’s install all necessary dependencies with
python -m venv functions/venv
source functions/venv/bin/activate && python -m pip install -r functions/requirements.txt
Now, let’s write some Python code for our cloud function. For this example, let’s create a simple function that responds to HTTP requests with a friendly greeting.
Navigate to the functions
directory created by the Firebase CLI and open the main.py file. Replace the contents with the following Python code:
from firebase_functions import https_fn
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, Firebase Cloud Functions with Python'@https_fn.on_request(max_instances=1)
def articles(req: https_fn.Request) -> https_fn.Response:
with app.request_context(req.environ):
return app.full_dispatch_request()
The code above will wrap your Flask python framework inside the Firebase Cloud Functions. which means
“ 1 Cloud Function can wrap multiple Flask API Endpoints”
For an example, we have a cloud functions named “articles” where we can have several API endpoints such as
– /contents
– /images
– /generators etc.
I other words, you can also treat a Cloud Functions stand as a Microservice, where they had their own responsibility for the scope and contents.
With our function ready, it’s time to deploy it to Firebase. Run the following command from your project directory to deploy your function
firebase deploy --only functions
Once deployed, you can test your cloud function by sending an HTTP request to its trigger URL. You can find the URL in the Firebase console under the “Functions” tab.
Now, open your favorite browser or use a tool like cURL to send a GET request to the trigger URL. You should receive a friendly greeting in response!
curl https://YOUR_CLOUD_FUNCTION_ID.run.app/YOUR_API_NAME
Congratulations! You’ve successfully built and deployed your first cloud function with Python using Firebase Cloud Functions.
Now you can hit your deployed cloud functions through Postman as well which in my case I have a POST API called /generate to generate articles with Generative AI. I will share more about this in another article!
So, In summary, we have learned :
– Understand the benefit of using serverless over microservice
– Setup Firebase Cloud Functions using Python
– Integrate Flask into our Python Firebase Cloud Functions.
– Deploy our Flask Firebase Cloud Functions
If you need the source code feel free to fork it from here : https://github.com/retzd-tech/genai-openai-firebase-function-sample
That’s it!
If you are up for next level, you can implement a more intelligent AI LLM Model, feel free to read it here!
whether you’re building a Generative AI Application, web application, processing data, or automating tasks, Firebase Cloud Functions with Python have got you covered. Happy coding in the cloud!