# Get started: write, test, and deploy your first functions

To get started with Cloud Functions, try working through this tutorial, which starts with the required setup tasks and works through creating, testing, and deploying two related functions:

- An "add message" function that exposes a URL that accepts a text value and writes it to Cloud Firestore.
- A "make uppercase" function that triggers on a Cloud Firestore write and transforms the text to uppercase.

Here's the full sample code containing the functions:

## Node.js
```javascript
// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const {logger} = require("firebase-functions");
const {onRequest} = require("firebase-functions/https");
const {onDocumentCreated} = require("firebase-functions/firestore");

// The Firebase Admin SDK to access Firestore.
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");

initializeApp();

// Take the text parameter passed to this HTTP endpoint and insert it into
// Firestore under the path /messages/:documentId/original
exports.addmessage = onRequest(async (req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push the new message into Firestore using the Firebase Admin SDK.
  const writeResult = await getFirestore()
      .collection("messages")
      .add({original: original});
  // Send back a message that we've successfully written the message
  res.json({result: `Message with ID: ${writeResult.id} added.`});
});

// Listens for new messages added to /messages/:documentId/original
// and saves an uppercased version of the message
// to /messages/:documentId/uppercase
exports.makeuppercase = onDocumentCreated("/messages/{documentId}", (event) => {
  // Grab the current value of what was written to Firestore.
  const original = event.data.data().original;

// Access the parameter `{documentId}` with `event.params`
  logger.log("Uppercasing", event.params.documentId, original);

const uppercase = original.toUpperCase();

// You must return a Promise when performing
  // asynchronous tasks inside a function
  // such as writing to Firestore.
  // Setting an 'uppercase' field in Firestore document returns a Promise.
  return event.data.ref.set({uppercase}, {merge: true});
});
```

## Python
```python
# The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
from firebase_functions import firestore_fn, https_fn

# The Firebase Admin SDK to access Cloud Firestore.
from firebase_admin import initialize_app, firestore
import google.cloud.firestore

app = initialize_app()

@https_fn.on_request()
def addmessage(req: https_fn.Request) -> https_fn.Response:
    """Take the text parameter passed to this HTTP endpoint and insert it into
    a new document in the messages collection."""
    # Grab the text parameter.
    original = req.args.get("text")
    if original is None:
        return https_fn.Response("No text parameter provided", status=400)

firestore_client: google.cloud.firestore.Client = firestore.client()

# Push the new message into Cloud Firestore using the Firebase Admin SDK.
    _, doc_ref = firestore_client.collection("messages").add({"original": original})

# Send back a message that we've successfully written the message
    return https_fn.Response(f"Message with ID {doc_ref.id} added.")

@firestore_fn.on_document_created(document="messages/{pushId}")
def makeuppercase(event: firestore_fn.Event[firestore_fn.DocumentSnapshot | None]) -> None:
    """Listens for new documents to be added to /messages. If the document has
    an "original" field, creates an "uppercase" field containg the contents of
    "original" in upper case."""

# Get the value of "original" if it exists.
    if event.data is None:
        return
    try:
        original = event.data.get("original")
    except KeyError:
        # No "original" field, so do nothing.
        return

# Set the "uppercase" field.
    print(f"Uppercasing {event.params['pushId']}: {original}")
    upper = original.upper()
    event.data.reference.update({"uppercase": upper})
```

## About this tutorial

We've chosen Cloud Firestore and HTTP-triggered functions for this sample in part because these background triggers can be thoroughly tested through the [Firebase Local Emulator Suite](/content/docs/emulator-suite/index.html). This toolset also supports Realtime Database, Cloud Storage, PubSub, Auth, and HTTP callable triggers. Other types of background triggers such as Remote Config and TestLab triggers can be tested interactively using toolsets not described in this page.

The following sections of this tutorial detail the steps required to build, test, and deploy the sample.

## Create a Firebase Project

Follow these steps if you're new to Firebase or Google Cloud.

1. Sign into the [Firebase console](https://console.firebase.google.com/).
2. Click the button to create a new Firebase project.
3. In the text field, enter a **project name**.
4. If prompted, review and accept the [Firebase terms](/content/terms/index.html), then click **Continue**.
5. _(Optional)_ Enable AI assistance in the Firebase console (called "Gemini in Firebase"), which can help you get started and streamline your development process.
6. _(Optional)_ Set up Google Analytics for your project, which enables an optimal experience using these Firebase products: [Firebase A/B Testing](/content/docs/ab-testing/index.html), [Cloud Messaging](/content/docs/cloud-messaging/index.html), [Crashlytics](/content/docs/crashlytics/index.html), [In-App Messaging](/content/docs/in-app-messaging/index.html), and [Remote Config](/content/docs/remote-config/index.html).
7. Click **Create project**.

Firebase creates your project, provisions some initial resources, and enables important APIs. When the process completes, you'll be taken to the overview page for your Firebase project in the Firebase console.

## Set up your environment and the Firebase CLI

You'll need a [Node.js](https://nodejs.org/) environment to write functions, and you'll need the Firebase CLI to deploy functions to the Cloud Functions runtime. For installing Node.js and [npm](https://www.npmjs.com/), [Node Version Manager](https://github.com/creationix/nvm/blob/master/README.md) is recommended.

Once you have Node.js and npm installed, [install the Firebase CLI](/content/docs/cli?#setup_update_cli/index.html) via your preferred method. To install the CLI via npm, use:

```
npm install -g firebase-tools
```

This installs the globally available firebase command. If the command fails, you may need to [change npm permissions](https://docs.npmjs.com/getting-started/fixing-npm-permissions).

You'll need a [Python](https://python.org/) environment to write functions, and you'll need the Firebase CLI to deploy functions to the Cloud Functions runtime. We recommend using `venv` to isolate dependencies. Python versions 3.10 through 3.13 are supported.

## Initialize your project

When you initialize Firebase SDK for Cloud Functions, you create an empty project containing dependencies and some minimal sample code. If you are using Node.js, you can choose either TypeScript or JavaScript for composing functions. For the purposes of this tutorial, you'll also need to initialize Cloud Firestore.

After these commands complete successfully, your project structure looks like this:
```
myproject
+- .firebaserc    # Hidden file that helps you quickly switch between projects with `firebase use`
|
+- firebase.json  # Describes properties for your project
|
+- functions/     # Directory containing all your functions code
      |
      +- .eslintrc.json  # Optional file containing rules for JavaScript linting.
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- index.js      # Main source file for your Cloud Functions code
      |
      +- node_modules/ # Directory where your dependencies (declared in package.json) are installed
```

## Import the required modules and initialize an app

After you have completed the setup tasks, you can open the source directory and start adding code as described in the following sections. For this sample, your project must import the Cloud Functions and Admin SDK modules. Add lines like the following to your source file:

```javascript
// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const {logger} = require("firebase-functions");
const {onRequest} = require("firebase-functions/https");
const {onDocumentCreated} = require("firebase-functions/firestore");

initializeApp();
```

These lines load the required modules and initialize an `admin` app instance from which Cloud Firestore changes can be made.

## Add the "add message" function

For the "add message" function, add these lines to your source file:

```javascript
// Take the text parameter passed to this HTTP endpoint and insert it into
// Firestore under the path /messages/:documentId/original
exports.addmessage = onRequest(async (req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push the new message into Firestore using the Firebase Admin SDK.
  const writeResult = await getFirestore()
      .collection("messages")
      .add({original: original});
  // Send back a message that we've successfully written the message
  res.json({result: `Message with ID: ${writeResult.id} added.`});
});
```

## Add the "make uppercase" function

For the "make uppercase" function, add these lines to your source file:

```javascript
// Listens for new messages added to /messages/:documentId/original
// and saves an uppercased version of the message
// to /messages/:documentId/uppercase
exports.makeuppercase = onDocumentCreated("/messages/{documentId}", (event) => {
  // Grab the current value of what was written to Firestore.
  const original = event.data.data().original;

// Access the parameter `{documentId}` with `event.params`
  logger.log("Uppercasing", event.params.documentId, original);

const uppercase = original.toUpperCase();

## Emulate execution of your functions

The [Firebase Local Emulator Suite](/content/docs/emulator-suite/index.html) allows you to build and test apps on your local machine instead of deploying to a Firebase project. Local testing during development is strongly recommended, in part because it lowers the risk from coding errors that could potentially incur cost in a production environment.

To emulate your functions:

1. Run `firebase emulators:start` and check the output for the URL of the Emulator Suite UI.
2. Create a new message by opening the URL in a new tab in your browser.
3. View the effects of the functions in the Emulator Suite UI:
   - In the **Logs** tab, you should see new logs indicating that your HTTP functions ran successfully.
   - In the **Firestore** tab, you should see a document containing your original message as well as the uppercased version of your message.

## Deploy functions to a production environment

Once your functions are working as desired in the emulator, you can proceed to deploying, testing, and running them in the production environment. Keep in mind that to deploy in production, your project must be on the [Blaze pricing plan](/content/pricing/index.html).

To complete the tutorial, deploy your functions and then execute them:

1. Run this command to deploy your functions:
```
firebase deploy --only functions
```

2. Using the URL output by the CLI, add a text query parameter, and open it in a browser.

## Next steps

In this documentation, you can learn more about how to [manage functions](/content/docs/functions/manage-functions/index.html) for Cloud Functions as well as how to handle all event types supported by Cloud Functions.
