Send firebase cloud messaging push notification from java server

How To Send Firebase Push Notification From App Server Tutorial

How to send Firebase push notification to your Android or iOS client from application server example.

I will give you an example of How to send firebase push notification to Android or iOS devices from PHP, Java,  C# or using Rest Client.

Here is Rest API example which we will use to send notifications to our client application. You can implement this Rest API in your application server.



Header :

Content-Type: application/json

Authorization: Server Key

(e.g key=AIzaSyD_Vw3Zf8XXXSDMSDKLMGyqR_Kyw5o)

You can find Servery key under Settings >Cloud messaging > Server key

Body :

You can send two types of data in request body.

1. Notification payload. (if you send notification using firebase console. It also sends notification payload.

    Firebase SDK at client side do not handle or receive a push notification from the server.

    Instead, Notification is passed to the Android OS for displaying in the notification panel.)

2. Data payload. (If you want to handle notification in your client application you should send data payload)

You can read about the difference in notification payload and data payload from this tutorial.

We will send data payload as Notification data payload.


{ “data”: 
 “title”: “Firebase notification”,
 “detail”: “I am firebase notification. you can customise me. enjoy”,
 “to” : “efaOvIXDbik:APA91bEkNUVWNaoA….”

to = your application firebase token.

where to get this firebase token?

In Android Apps which handles firebase push notification.

•On Initial startup of the Project Application, Firebase SDK will generate a unique device token inside method onTokenRefreshed.

override onTokenRefreshed(String token) 
  // from here you can save application token in your app server.

will be called whenever a token is updated or generated.

And you have to save this token in your application server.

Above example is to send notification to single device.

Here is a rest client screenshot for more clarification.

Sending Firebase Push Notification from server

How to Send push notification to all users or multiple devices from server side?

We already discussed how to send a push notification to the single device.

There are 2 ways of sending push notification to all devices or users from your app server using FCM.

  1. Using all firebase token’s and put them in registration_ids array.

You have to pass firebase registration tokens in registration_ids Array.

"registration_ids": [
"priority": "high",

"data": {
"title": "Firebase Notification Example",
"detail": "This firebase push notification will be sent to all firebase tokens (devices) registered with your app server."

2. Topics

Now the second method is Topics.

  • Topics are just keys which users subscribe to. Users have to subscribe to any topic.
  • Users can subscribe to any existing topic or can create a new topic and than subscribe to it.

To subscribe to any topic. users/client use this code (this is Android Code)


HTTP POST REQUEST SAMPLE for send firebase push notification to all users who subscribed to news topic.

Body :
  "to": "/topics/news",
  "data": {
    "message": "This is a FCM Topic Message!",

You can implement this code in your application server.

Now all users/ devices who subscribed to  topic “news” topic will receive a push notification.

Now we will write Java client code which will send Firebase (FCM) Push Notification and you can use this code  example in your application server.


Step 1-

First of all, create a new project in your IDE (I used IntelliJ IDEA).

Step 2- Setup Gradle dependencies

Add below dependencies in your project.

  1. Javax Annotation
  2. Google Gson
  3. Apache HttpClient
group 'pushnotification'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile 'javax.annotation:javax.annotation-api:1.2'
    compile ''
    compile 'org.apache.httpcomponents:httpclient:4.5.4'


Step 3- Create Model / POJO classes for FCM Notification Data payload

import javax.annotation.Generated;

public class NotificationData {

    private String mDetail;

    private String mTitle;

    public String getDetail() {
        return mDetail;

    public void setDetail(String detail) {
        mDetail = detail;

    public String getTitle() {
        return mTitle;

    public void setTitle(String title) {
        mTitle = title;


import javax.annotation.Generated;

public class NotificationRequestModel {

    private NotificationData mData;
    private String mTo;

    public NotificationData getData() {
        return mData;

    public void setData(NotificationData data) {
        mData = data;

    public String getTo() {
        return mTo;

    public void setTo(String to) {
        mTo = to;

Step 4- Sending Firebase Push Notifications API using Java Http Client

Create a new Application Class inside the main package of your project.

import model.NotificationData;
import model.NotificationRequestModel;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.lang.reflect.Type;

public class ApplicationClass {

    public static void main(String[] args) throws IOException {

        System.out.println("Welcome to Developine");

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(

        // we already created this model class.
        // we will convert this model class to json object using google gson library.

        NotificationRequestModel notificationRequestModel = new NotificationRequestModel();
        NotificationData notificationData = new NotificationData();

        notificationData.setDetail("this is firebase push notification from java client (server)");
        notificationData.setTitle("Hello Firebase Push Notification");

        Gson gson = new Gson();
        Type type = new TypeToken<NotificationRequestModel>() {

        String json = gson.toJson(notificationRequestModel, type);

        StringEntity input = new StringEntity(json);

        // server key of your firebase project goes here in header field.
        // You can get it from firebase console.

        postRequest.addHeader("Authorization", "key=AAAA7-UgB34:APA91bFhpZ1-MYyFfQd2gof0vUAFKNcQCmmf_10acMn-HS_0iBBvP");

        System.out.println("reques:" + json);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        } else if (response.getStatusLine().getStatusCode() == 200) {

            System.out.println("response:" + EntityUtils.toString(response.getEntity()));

Simply Run this code and it will send Firebase Push Notification to your Android/iOS application using Firebase Server.

This will be the output of above Java code.

Welcome to Developine
request:{"data":{"detail":"this is firebase push notification from java client (server)","title":"Hello Firebase Push Notification"},"to":"eHp6V2Wtr4I:APA91b4tPNStf-vFTGNy8RSbZKz"}

I copied token of a single user manually and used in above code.

In a real-world project, you have to send Firebase token which is generated on the client side (Mobile App) to your application server.


We first learned how we can send Firebase push notification using Rest Client.

We also learned how to send Firebase Push Notification from java client using firebase server.

Recommended Reading:-

How to setup firebase push notification in Android

If this helped you share this article and subscribe to our website for latest updates on Kotlin, Android, Spring Boot.

Hello! I am Hammad Tariq. Jack of All trades and Yet master of Many! Senior Android Application Developer | Cross-platform Development | Flutter | Backend Development (Spring Boot + Kotlin + MySQL) | Blogger | Founder I am an all-around Mobile Developer who is passionate about learning the latest technologies and trends. I graduated from Air University Islamabad, Pakistan in 2015 but started working on Android Development, Universal Windows Apps development long before that. Currently, I am working as a team lead and Senior Android Developer at EVAMP SAANGA, Pakistan.
Posts created 42

21 thoughts on “How To Send Firebase Push Notification From App Server Tutorial

  1. how to pass data like employee id and name in data.?

    { “data”:
    “title”: “Firebase notification”,
    “detail”: “I am firebase notification. you can customise me. enjoy”,
    “to” : “efaOvIXDbik:APA91bEkNUVWNaoA….”

    1. Hi Mano sorry for late reply. you are doing it in the right way.
      data payload will be received by your application and you have to parse it as json.

  2. notificationRequestModel.setTo(“eHp6V2Wtr4I:APA91bFLHRuScumQB0lnNRmeirxu5kV2lUPDZ8SbZKz”);
    setTo ? what…
    Can you please tell me what is the eHp6V2Wtr4I:APA91bFLHRuScumQB0lnNRmeirxu5kV2lUPDZ8SbZKz

    Thank you

  3. Hi ,

    Are we using “Authorization:key=AIswgdyZ-4f…0HPYzPDSKNSSaA” for the authentication purpose? or any other authentication option we can use in rest call?

    Please carify below mentioned point:
    •On Initial startup of project Firebase SDK will generate a unique device token. override method onTokenRefreshed() will be called whenever a token is updated or generated. is it mandatory?

  4. Yes each project at firebase has unique authorization key.
    you need this authorization key when you have to send firebase push notification from application server to your Android or iOS app.

    this is code snippet from firebase android client.
    firebase sdk generate a token for each device which register itself for handling and receving firebase push notifications.
    this token is used to send firebase push notification to single device from firebase console or from firebase app server.

  5. thanks a lot for that useful topic,,,
    Code run successfully and the result was
    — i checked the Token-id
    and the server key in >>> Project Settings >>> Cloud Messaging >>> copied the Server Key Token

    but no notification was delivered on my android app 🙁

      1. i did as the above code of the ApplicationClass ,,, i tested the Token from the Firebase API on the console “” and i could recieve the notification on my android while the APP is in forground or background
        but using the Code and the Server the reply is

        reques:{“data”:{“detail”:”this is firebase push notification from java client (server)”,”title”:”Hello Firebase Push Notification”},”to”:”c_qmaestHZc:APA91bHaWCVmu4e13vzkk4Lj6v0_VCAL7lybvabM8S4jRRfrkOlhd3dZKHKsMNCWJ3TR-7EYi_srMs8C89OO9yNCRt1bEYD-coJncLhF70wskpgFYzC_8Uv0wdhKYJrXdV7mKMTWvE”}


        for Authentication i used the Server key in Project Settings >>> Cloud Messaging >>> Project credentials >>> then copied the Value of Server Key

        and why the notification is received from the Console and Not Received from the Code ? 🙁

        thanks in advance

        1. If you send notification from firebase console it will always be “Notification Payload”.
          and using code in ApplicationClass you are sending data payload.
          Make sure to check your Android app logs. You have received notification actually in onMessageReceived() function.
          But you have to parse its json and display it using local notification manager class, means Firebase SDK will not send notification to Android OS for displaying, you have to do it yourself.

          I hope your concepts will be clear now. 🙂

  6. Hello sir i integrated your source code,also get response but when i send notificatin through one devise it will not received by other devices.i have also integrate recieved notification same app.

    1. Hi Santosh,
      I am sorry I am unable to understand your query. what does this mean notification sent through one device is not received on other devices.
      You are trying to send a push notification to a single device using my code? or you want to send notification to multiple devices?

  7. Hi Team,

    We are facing issue while sending push notification to ISO Device. IPhone 7 with IOS 12X version.
    It was working absolutly fine till few days back. now its not working and we are getting success response.

    Do let us know if any change is required to do so.

    1. Hi Santosh, sorry for the late reply. Maybe there is some change in Apple Push Notification Services.
      The code for sending push notification is the same. It should work regardless of Android or iOS.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top