This quickstart shows how to write callable functions with the Firebase SDK for Cloud Functions in Python. Callable functions are HTTPS functions that your app calls with a Firebase client SDK, which handles the request format and passes along the user's authentication state.
Read more about callable functions
See functions/main.py for the code. It defines two functions:
addnumbers: Adds two numbers,firstNumberandsecondNumber, passed in the request data and returns the result. It raises anHttpsErrorwith theINVALID_ARGUMENTcode if either number is missing.addmessage: Saves a message to the Realtime Database after removing swear words. The function requires the caller to be signed in and records the caller's user ID, name, picture, and email with the message.
-
Create a Firebase project in the Firebase console and enable the Realtime Database.
-
Install the Firebase CLI and sign in with
firebase login. -
Clone this repo and open the
Python/quickstarts/callable-functionsdirectory. -
Select your project with
firebase use --add. -
Create a virtual environment and install the dependencies:
cd functions python3 -m venv venv source venv/bin/activate pip install -r requirements.txt cd ..
-
Deploy with
firebase deploy --only functions.
Callable functions use a specific request format: a POST request with a JSON body whose payload sits under a data key, plus a few headers the client SDKs set for you. The Testing tab in the Google Cloud console doesn't follow that format, so calls from there fail. Use one of the following instead.
Call the function from your app with a Firebase client SDK, for example with the Web SDK:
import { getFunctions, httpsCallable } from "firebase/functions";
const addNumbers = httpsCallable(getFunctions(), "addnumbers");
const result = await addNumbers({ firstNumber: 1, secondNumber: 2 });
console.log(result.data.operationResult); // 3The addmessage function requires a signed-in user, so sign in with Firebase Authentication before you call it. The SDK attaches the user's ID token to the request.
For a quick check of addnumbers, which doesn't require authentication, send the callable request format yourself. Run the function in the Local Emulator Suite:
firebase emulators:start --only functionsThen call it:
curl -X POST http://127.0.0.1:5001/YOUR_PROJECT_ID/us-central1/addnumbers \
-H "Content-Type: application/json" \
-d '{"data": {"firstNumber": 1, "secondNumber": 2}}'The response wraps the function's return value in a result key:
{"result": {"firstNumber": 1, "secondNumber": 2, "operator": "+", "operationResult": 3}}The same request works against the deployed function at its https:// URL, which firebase deploy prints.
© Google, 2023. Licensed under an Apache-2 license.