Firebase : Send notification with REST API
Asked Answered
M

9

47

Is it possible to send push notification with REST API on Firebase? I can send notifications with Firebase console but i need to send notifications with REST API.

Mombasa answered 27/5, 2016 at 19:2 Comment(1)
Sending Firebase Notifications is only supported from the Firebase Console. But you accomplish the same by using Firebase Cloud Messaging, which has an API you can call (and is what Firebase Notifications are built on).Elaelaborate
O
16

this may help - https://firebase.google.com/docs/cloud-messaging/http-server-ref where sample message you can find here - https://firebase.google.com/docs/cloud-messaging/downstream

from Firebase console you can get Server Key as an authorization you put in the http header, in the tab Cloud messaging.

Overwind answered 2/8, 2016 at 16:51 Comment(0)
B
130

Just for helping,

If anyone wants to use REST POST API, here it is, use the Postman with below configuration

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

Header:

"Content-Type": "application/json",
"Authorization": "key=<Server_key>"

BODY:

{
    "to": "<Device FCM token>",
    "notification": {
      "title": "Check this Mobile (title)",
      "body": "Rich Notification testing (body)",
      "mutable_content": true,
      "sound": "Tri-tone"
      },

   "data": {
    "url": "<url of media image>",
    "dl": "<deeplink action on tap of notification>"
      }
}

That's it. Thanks!!!

If you want to get more details about Rich Notification with FCM, you can check my article on Medium Rich Push Notification with Firebase Cloud Messaging (FCM) and Pusher on iOS platform

Bullwhip answered 2/2, 2019 at 7:11 Comment(6)
How to manage this device FCM token ? In my case, i wants to store it in mongo db on every login. is it fine ?Ignace
@SumanthVarada You can use any database to save the fcm token even Firebase database. fcm token is derived from device token, sent by APNS while registering for Remote notification which is constant until you delete the application and install a fresh one. You can do a local check while log in that fcm_token changed or not? If changed then make a server call to update else it's unnecessary to update the same information again.Bullwhip
@KakiMasterOfTime for rich notification in iOS, people already reported to Firebase but the functionality yet to provide by Firebase console.(github.com/firebase/quickstart-ios/issues/…) Agree with you. Maybe in future Firebase will be smart enough to do all of these?Bullwhip
@AshisLaha Thank you so much! I looked at the Firebase docs and just needed one example. You made my daySubjectivism
@AshisLaha Can we add multiple tokens ? For example I want to send notifications to 5 users.Pruett
Where do I get the key for authorization. I tried to use the private key from firebase admin json file. That is not correct.Rodenticide
P
20

I used the below rest API to send notification.

curl -X POST \
  https://fcm.googleapis.com/fcm/send \
  -H 'Authorization: key=AAAAG-oB4hk:APA91bFUilE6XqGzlqtr-M-LRl1JisWgEaSDfMZfHuJq3fs7IuvwhjoGM50i0YgU_qayJA8FKk15Uvkuo7SQtQlVt4qdcrrhvnfZyk_8zRGAskzalFUjr2nA2P_2QYNTfK6X8GbY0rni' \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: c8af5355-dbf2-4762-9b37-a6b89484cf07' \
  -H 'cache-control: no-cache' \
  -d '{
    "to": "ey_Bl_xs-8o:APA91bERoA5mXVfkzvV6I1I8r1rDXzPjq610twte8SUpsKyCuiz3itcIBgJ7MyGRkjmymhfsceYDV9Ck-__ObFbf0Guy-P_Pa5110vS0Z6cXBH2ThnnPVCg-img4lAEDfRE5I9gd849d",
    "data":{
        "body":"Test Notification !!!",
        "title":"Test Title !!!"
    }

}'

Authorization : key=AAAAG-oB4hk:APA91bFUilE6XqGzlqtr-M-LRl1JisWgEaSDfMZfHuJq3fs7IuvwhjoGM50i0YgU_qayJA8FKk15Uvkuo7SQtQlVt4qdcrrhvnfZyk_8zRGAskzalFUjr2nA2P_2QYNTfK6X8GbY0rni

where key is web_server_key from the console and you need to specify the unique registration key which you will get from the app.

enter image description here

"to": "ey_Bl_xs-8o:APA91bERoA5mXVfkzvV6I1I8r1rDXzPjq610twte8SUpsKyCuiz3itcIBgJ7MyGRkjmymhfsceYDV9Ck-__ObFbf0Guy-P_Pa5110vS0Z6cXBH2ThnnPVCg-img4lAEDfRE5I9gd849d" is the FCM registration token from device. Please refer to the below link.

https://firebase.google.com/docs/cloud-messaging/android/client?authuser=0

Perplexity answered 24/1, 2019 at 8:19 Comment(2)
At least on iOS the "data" key should be "notification" for it to show up. The "data" key is for custom data and I don't see the notification when testing without the "notification" key.Rectory
There is no server key in this tab.Hakodate
O
16

this may help - https://firebase.google.com/docs/cloud-messaging/http-server-ref where sample message you can find here - https://firebase.google.com/docs/cloud-messaging/downstream

from Firebase console you can get Server Key as an authorization you put in the http header, in the tab Cloud messaging.

Overwind answered 2/8, 2016 at 16:51 Comment(0)
Y
10

Try this,

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

Method - Post

Headers

  • Authorization -> key= Server Key which you can get it from console
  • Content-Type -> application/json

Body

{
 "to" : "FCM Token goes here",
 "notification" : {
     "body" : "New Lesson Added 1",
     "title": "Lokesh"
 }
}
Yawning answered 16/8, 2021 at 9:43 Comment(0)
L
10

The new version of API (called v1) creates more challenges to send a message via ARC. You need a special token, which will expire. You have to create firebase admin sdk key(service account key) in firebase console:

Firebase-admin sdk

They key is stored in json format something like this:

 {
  "type": "service_account",
  "project_id": "<your project ID>",
  "private_key_id": "8b..............................37",
  "private_key": "-----BEGIN PRIVATE KEY-----
  MIIE.....
  ....
  -----END PRIVATE KEY-----\n",
  "client_email": "firebase-adminsdk-6fzie@<yourprojectID>.iam.gserviceaccount.com",
  "client_id": "1...................4",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": 
  "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk- 
  6fzie%40<yourprojectID>.iam.gserviceaccount.com"
  } 

The key is used to identify you while obtaining token for http communication. You need a kind of server access to firebase. I have used python in WSL with this piece of code:

import requests
import google.auth.transport.requests

from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']

credentials = service_account.Credentials.from_service_account_file('service-account.json', scopes=SCOPES)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
print(credentials.token)

Where service-account.json is your private key in file on your filesystem where python is running. You will get the token and it could be used inside ARC:

ya29.c.b0Aa9VdylWfrAFWysdUeh3m7cGF-Cow1OAyyE4bEqFL....................48Ye7w

ARC config is similar like in legacy API, but there are some changes. The URL has changed and it contains your project ID:

https://fcm.googleapis.com/v1/projects/<your project ID>/messages:send

We still use POST method and headers have only one line Content-Type application/json. The authentication has a separated tab and we are supposed to use Bearer + token from python:

Firebase authentication

It is important to select Bearer and enable it, because it is disabled by default.

The changes are in the body as well. This is an example of the message to individual application based on application token:

   {
      "message" : {
        "token" : "e6e....FurF",
        "notification" : {
          "body" : "Great deal!",
          "title" : " Buy everything"
       }
     }
    }

where keyword "to" has changed to "token". That's all and we can send the message to the app. I wanted to have it here to be able to migrate to API v1 as Goggle requires these days. The last piece of code is for curl:-)

curl " https://fcm.googleapis.com/v1/projects/<your project id>/messages:send" \
  -X POST \
  -d "{\r\n  \"message\" : {\r\n    \"token\" : \"e6e....FurF\",\r\n    \"notification\" : {\r\n      \"body\" : \"Great deal!\",\r\n      \"title\" : \" Buy everything\"\r\n   }\r\n }\r\n}" \
  -H "Content-Type: application/json" \
  -H "authorization: Bearer ya29.c.b...."

Here is source I have used:

Firebase cloud messaging doc

GIT HUB code for messaging

Lamoree answered 9/12, 2022 at 17:28 Comment(1)
Thank you for this. Any example of how to get the access token from service-account.json using a php based server/code?Ricoriki
E
8

Using ARC For Sending Request to Firebase Console To Send Notification Using ARC For Sending Request to Firebase Console To Send Notification

You can use ARC OR Postman or your own server to send notification. You need to collect your web_server_key from the console and you need to specify the unique registration key which you will get from the app when calling the onRefreshToken() method.

You need to send the request to https://fcm.googleapis.com/fcm/send with Content-Type : json and Authorization: web_server_key. On To value user your app_registration_token .

Emyle answered 11/4, 2017 at 6:52 Comment(2)
i want to send notifications to all the clients.So what would be "to" valueElamite
Then you need to create a topic . You can create or subscribe topic from your java code. The users that are subscribed to this specific topic can get the notification. If you want to send the notification to all users then create one topic and subscribe it from your java code. Reference - firebase.google.com/docs/notifications/android/console-topicsEmyle
M
3

We used the following documentation to send notifications from a web client.

There is an easy way to send a notification via Chrome App or Extension.

function sendMessage() {
  var message = {
    messageId: getMessageId(),
    destinationId: senderId + "@gcm.googleapis.com",
    timeToLive: 86400,    // 1 day
    data: {
      "key1": "value1",
      "key2": "value2"
    }
  };
  chrome.gcm.send(message, function(messageId) {
    if (chrome.runtime.lastError) {
      // Some error occurred. Fail gracefully or try to send
      // again.
      return;
    }
Montespan answered 30/6, 2016 at 8:3 Comment(0)
T
3

For c# application (Xamarin.Forms etc.) you can just copy this code:

 public async static void SendPushToTokenID(string tokenID, string title, string body)
        {

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

            var url = serverURL;
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + serverKey);


            var notification = new
            {
                title = title,
                body = body

            };

            var postModel = new
            {
                to = tokenID,
                notification = notification

            };


            var response = await client.PostAsJsonAsync(url, postModel);

            // format result json into object 
            string content = await response.Content.ReadAsStringAsync();
            string xw = (response.Content.ReadAsStringAsync().Result);

        }

for url use: https://fcm.googleapis.com/fcm/send and for your server key use your firebase server key. thats literally all. just dont forget to store the device token ID on your server and then you can send messages all day for free to individual users. its dead simple.

Tonitonia answered 22/6, 2021 at 14:25 Comment(0)
D
0

For new verson of fcm api v1 Http kotlin code to get the server authentication key

class FcmAccessTokenManager(){

    private val firebaseMessagingScope = "https://www.googleapis.com/auth/firebase.messaging"

    fun getAccessToken(): String? {
     return try {
        val jsonString = """
            //past your firebase service generated key gson content here
        """.trimIndent()

        val stream = ByteArrayInputStream(jsonString.toByteArray(StandardCharsets.UTF_8))
        val googleCredentials = GoogleCredentials.fromStream(stream)
            .createScoped(Lists.newArrayList(firebaseMessagingScope))
        googleCredentials.refresh()
        googleCredentials.accessToken.tokenValue
    } catch (e: IOException) {
        Log.d("access token error", e.localizedMessage ?: "Error occurred")
        null
    }
}}
Darfur answered 14/6 at 1:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.