Pushing Notification to all users in Firebase

Viewed 3477

I am trying to send push notifications using python to all users. However, I am aware that there is no way to do this using apps and you have to use topics (as far as I am aware). Is there a way that I can create a topic out of the app? Thanks Edit: I am completely new to firebase (so sorry if I am difficult)

3 Answers

First of all you need to understand a topic does not need to create (it will be create automatically), you only need to define the topic name for example if you are creating app to receive push notification when the weather change, so the topic name could be "weather".

Now you need have 2 components: mobile & backend

1. Mobile: in your mobile app you only need integrate the Firebase SDK and subscribe to the topic "weather" how do you do that?

Firebase.messaging.subscribeToTopic("weather")

Don't forget checking documentation.

2. Backend: in your server you will need to implement the sender script based on FCM SDK. If you are a beginner I'd recommend you use Postman to send push notifications and then integrate FCM in your backend app.

You can send this payload trough Postman (don't forget set your API KEY in headers)

https://fcm.googleapis.com/fcm/send

{
  "to": "/topics/weather",
  "notification": {
    "title": "The weather changed",
    "body": "27 °C"
  }
}

If that works, you can add FCM SDK to your backend:

$ sudo pip install firebase-admin
default_app = firebase_admin.initialize_app()

Finally you can send notifications as documentation says:

from firebase_admin import messaging

topic = 'weather'

message = messaging.Message(
    notification={
        'title': 'The weather changed',
        'body': '27 °C',
    },
    topic=topic,
)
response = messaging.send(message)

More details here: https://github.com/firebase/firebase-admin-python/blob/eefc31b67bc8ad50a734a7bb0a52f56716e0e4d7/snippets/messaging/cloud_messaging.py#L24-L40

You need to be patient with the documentation, I hope I've helped.

The above solutions are depreciated and outdated.

Let me include the latest implementation of firebase-admin SDK for python.

import firebase_admin
from firebase_admin import credentials, messaging

cred = credentials.Certificate(
    "<path-to-your-credential-json>")
firebase_admin.initialize_app(cred)

topic = 'notification'

message = messaging.Message(
    notification=messaging.Notification(
        title='The weather changed', body='27 °C'),
    topic=topic,
)
response = messaging.send(message)

print(response)

*Note of few configurations:

  1. Obtain your credential.json in your firebase console under: "Project settings" -> "Service accounts" -> "Generate new private key"
  2. Make sure you subscribe to the correct topic name for both of your server and client application. Every client applications that subscribed to the same topic regardless of which devices will received the corresponding notifications.

Have a good day~

Related