RousselTMLEARNING

TP · Google Cloud: from discovery to expertise

Lab: An API on the Functions Framework with the Firestore emulator with correction

The correction is integrated into the TP (See the green boxes)

What you will learn in this TP
  • Use the Firestore emulator
  • Write a function with the Functions Framework
  • Prepare the container for Cloud Run

Introduction #

What you will learn in this section
  • Use the Firestore emulator
  • Write a function with the Functions Framework
  • Prepare the container for Cloud Run

Context. A product team wants a serverless user profile API. You build it entirely locally before any deployment.

Prerequisites: Docker, Python 3 and the Google Cloud SDK (gcloud with emulator components); no Google Cloud project or billing needed  ·  Estimated time: 50 min

An API that creates, reads and lists profiles in Firestore, run locally and in a container.

Hands-on #

Guided steps, with their solution.

  1. 1. Start the Firestore emulator

    Why? FIRESTORE_EMULATOR_HOST redirects the Python client.

    Start the emulator and install the libraries.
    See the correction
    gcloud components install cloud-firestore-emulator --quiet
    gcloud emulators firestore start --host-port=localhost:8086 &
    export FIRESTORE_EMULATOR_HOST=localhost:8086 GOOGLE_CLOUD_PROJECT=demo
    pip install functions-framework google-cloud-firestore
  2. 2. Write the function

    Why? The same code runs on Cloud Run functions unchanged.

    Create main.py: POST creates a profile, GET with ?id= reads it, GET without parameter lists profiles.
    See the correction
    import functions_framework
    from google.cloud import firestore
    
    db = firestore.Client()
    
    @functions_framework.http
    def profils(request):
        if request.method == "POST":
            donnees = request.get_json(silent=True) or {}
            ref = db.collection("profils").document()
            ref.set({**donnees, "cree": firestore.SERVER_TIMESTAMP})
            return {"id": ref.id}, 201
        pid = request.args.get("id")
        if pid:
            doc = db.collection("profils").document(pid).get()
            return (doc.to_dict(), 200) if doc.exists else ({"erreur": "introuvable"}, 404)
        return {"profils": [d.id for d in db.collection("profils").limit(20).stream()]}, 200
  3. 3. Run and test

    Why? functions-framework simulates the Google runtime.

    Run the function on port 8080, create a profile, read it back and list.
    See the correction
    functions-framework --target=profils --port=8080 &
    ID=$(curl -s -X POST localhost:8080 -H 'Content-Type: application/json' -d '{"nom":"Alice","role":"SRE"}' | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')
    curl -s "localhost:8080?id=$ID"
    curl -s localhost:8080
  4. 4. Containerise for Cloud Run

    Why? Cloud Run runs any container listening on $PORT.

    Write a Dockerfile, build the image and run it connected to the emulator.
    See the correction
    cat > Dockerfile <<'EOF'
    FROM python:3.12-slim
    WORKDIR /app
    RUN pip install --no-cache-dir functions-framework google-cloud-firestore
    COPY main.py .
    CMD exec functions-framework --target=profils --port=${PORT:-8080}
    EOF
    docker build -t profils:1.0 .
    docker run --rm --network host -e PORT=9090 -e FIRESTORE_EMULATOR_HOST=localhost:8086 -e GOOGLE_CLOUD_PROJECT=demo profils:1.0 &
    curl -s localhost:9090      # même API, servie par le conteneur
    # sur Google Cloud : gcloud run deploy profils --source . --region europe-west9

Difficulty level : ●●●○○ (3/5)

My progress

  • ⏱ Estimated time : ≈ 50 min

Sign in to track your progress and take notes. Sign in

💬 Ask a question

Recommended Articles

Le calcul sur Google Cloud : Compute Engine, GKE, Cloud Run et Cloud Functions

Choisir le calcul sur Google Cloud : VM Compute Engine et groupes d'instances gérés, Google Kuber...

Les bases de données Google Cloud : Cloud SQL, AlloyDB, Spanner, Firestore et Bigtable

Choisir une base de données sur Google Cloud : Cloud SQL et AlloyDB pour le relationnel, Spanner ...

Le stockage Google Cloud : Cloud Storage, disques persistants et Filestore

Stocker des données sur Google Cloud : Cloud Storage (classes, emplacements régionaux, birégionau...

Informatique serverless : définition, FaaS et cas d'usage

L'informatique serverless expliquée : Function as a Service (FaaS), fonctionnement, avantages, li...

Exploiter Google Cloud : observabilité, sécurité, infrastructure as code et coûts

Exploiter Google Cloud : Cloud Monitoring, Cloud Logging et Cloud Trace (Google Cloud Observabili...

Comprendre Google Cloud : régions, projets, hiérarchie, outils et tarification

Les bases de Google Cloud : régions et zones, hiérarchie organisation, dossiers et projets, API à...

Le réseau Google Cloud : VPC mondial, sous-réseaux, pare-feu et équilibrage

Concevoir le réseau sur Google Cloud : VPC mondial et sous-réseaux régionaux, règles de pare-feu ...

IAM sur Google Cloud : rôles, comptes de service et règles d'administration

Gérer les accès sur Google Cloud : principaux, rôles de base, prédéfinis et personnalisés, liaiso...

Préparer la certification Google Cloud Digital Leader

Guide de préparation au Cloud Digital Leader : format, domaines (transformation numérique, donnée...

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!