Send PUSH Notifications to Google Firebase Cloud Messaging API (V1) using Python

Tiempo de lectura: 3 minutos

Today we are going to learn how we can send a message to the Firebase Cloud Messaging endpoint using Python. (https://firebase.google.com/docs/cloud-messaging/http-server-ref?hl=es-419)

For this, we need the Google endpoint:

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send

And previously we have to generate a token in our application, for this we go to Firebase, select our project, and click on Project Settings:

Inside here, we look for Cloud Messaging

Now go to the Firebase Cloud Messaging (V1) API section

Click on Manage Service Accounts.

Go to your account and click on the 3-dot context menu:

and choose Manage Keys:

Now click on Add Key > Create new key:

Choose type JSON and click on create:

Save this JSON in the root of the project and create a file named send_push.py

-app.json
-send_push.py

Now we are going to create the code send_push.py

import json
import requests
import jwt
from datetime import datetime, timedelta

JSON_DIR = "app.json"

def send_cloud_message(title_send, message_send, token_send):
    access_token = get_access_token()
    project_id = get_data_json()["project_id"]

    url = f'https://fcm.googleapis.com/v1/projects/{project_id}/messages:send'

    data = {
        'message': {
            'token': token_send,
            'notification': {
                'title': title_send,
                'body': message_send,
            },
            'data': {
                'key_1': 'Value for key_1',
                'key_2': 'Value for key_2',
            },
        },
    }

    headers = {
        'Content-type': 'application/json',
        'Authorization': 'Bearer ' + access_token,
    }

    response = requests.post(url, json=data, headers=headers)

    # Handle the response as needed
    # You can print the result for debugging
    print(response.text)

def get_access_token():
    
    private_key = get_data_json()["private_key"]  # Replace with your private key
    cliend_id = get_data_json()["client_id"]  # Replace with your client email address

    now = datetime.utcnow()
    expiration_time = now + timedelta(hours=1)

    jwt_payload = {
        'iss': cliend_id,
        'scope': 'https://www.googleapis.com/auth/firebase.messaging',
        'aud': 'https://www.googleapis.com/oauth2/v4/token',
        'exp': expiration_time,
        'iat': now,
    }

    encoded_jwt = jwt.encode(jwt_payload, private_key, algorithm='RS256')

    data = {
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion': encoded_jwt,
    }

    response = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data)
    response_data = response.json()
    return response_data['access_token']

def get_data_json():
    with open(JSON_DIR) as json_file:
        data = json.load(json_file)
        return data

You will need to change JSON_DIR = “app.json” to the path of your JSON.

Additionally, you need to install jwt:

 pip install PyJWT

To send a message, you can use the following:

send_cloud_message('Message Title', 'Message Body', 'device_token')

For ‘device_token’, you’ll need to use a valid device token. Here’s how you can obtain it: https://devcodelight.com/?p=7128

Leave a Comment