Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Setting up Firebase Push notifications with a REST API

Introduction

Push notifications are a powerful tool that can bridge the communication gap between your front-end and back-end systems. These notifications offer a direct and immediate channel to engage with users across web and mobile platforms. Whether you’re running a web application, a mobile app, or a combination of both, implementing Push Notifications can enhance user engagement and provide real-time updates, making your application more relevant and user-friendly.

In the context of a Rest Api, a push notification could allow you to be notified each time a new user registers to your app, for example.

In this comprehensive guide, we will walk you through the process of setting up push notifications with a REST API, covering both the back-end and front-end aspects. By the end of this tutorial, you’ll have the knowledge and tools to deliver personalized and timely messages to your users, keeping them informed, engaged, and coming back for more.

Backend Setup

We won’t go over the process of setting up a REST API, but you can do so by using Spring Boot, Node.js, or any other web framework of your choosing. We are using Spring for this tutorial but the methods defined here are easily adaptable to other frameworks.

The overall process of sending a push notification consists in making a POST request on the firebase servers, with a JSON payload that looks like this:

{ "to": "deviceToken"   
"notification":{ 
"title": "notification Title"
"body": "Body",
"mutable_content": "true"  } }

Here’s a breakdown of the key-value pairs in the JSON object:

  • "to": This is where you specify the FCM token of the target device. It indicates the destination for the push notification.
  • "notification": This is an object containing the details of the notification to be displayed.
    • "title": The title of the notification, often displayed at the top of the notification.
    • "body": The body or content of the notification, which may include additional information like the user’s ID, username, and file path.
    • "mutable_content": This field indicates whether the content of the notification is mutable. A mutable notification allows you to update or modify the notification content after it’s been received by the device. Setting it to "true" means the content can be modified.

You will also need to retrieve the server key, from the firebase console, under Cloud Messaging in project settings:

https://console.firebase.google.com

You’ll find the server key , which you can copy and use in your requests.

You must then make a POST request to the following endpoint, with the JSON payload specified above:

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

You will also need to set the server key as a header.

For reference, a method creating such a request in Spring Boot is defined below:

public void sendPushNotification(String serverKey,String deviceToken,String title, String body){

String fcmUrl = "https://fcm.googleapis.com/fcm/send";
//Define the json payload:
Map message = new HashMap();
message.put("to", deviceToken);
Map notification = new HashMap();
notification.put("title", title);
notification.put("body", body);
notification.put("mutable_content", "true");
message.put("notification", notification);

try {
URL url = new URL(fcmUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// Set the request method to POST
conn.setRequestMethod("POST");

// Set the authorization header with your FCM server key
conn.setRequestProperty("Authorization", "key=" + serverKey);

// Set the content type to JSON
conn.setRequestProperty("Content-Type", "application/json");

// Enable input and output streams
conn.setDoOutput(true);

// Convert the message map to a JSON string
String jsonMessage = new Gson().toJson(message);

// Write the JSON payload to the output stream
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonMessage.getBytes("utf-8");
os.write(input, 0, input.length);
}

// Get the HTTP response code
int httpResponseCode = conn.getResponseCode();
System.out.println("FCM HTTP Response Code: " + httpResponseCode);

// Handle the response as needed
if (httpResponseCode == 200) {
System.out.println("Message sent successfully");
} else {
System.out.println("Error sending message");
}

conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}

}

What is the device token ?

It’s a token that is unique to the device to which you plan to send the notification to. Keep reading to see how to get this information on an android device.

Frontend Integration

To use firebase in your project, add the following line in your project grade, under plugins:

id ‘com.google.gms.google-services’ version ‘4.4.0’ apply false

In your module level gradle file, add the following line to plugins:

id ‘com.google.gms.google-services’

And the following lines to the dependencies:

implementation ‘com.google.firebase:firebase-messaging:23.2.1’
implementation platform(‘com.google.firebase:firebase-bom:32.2.2’)
implementation ‘com.google.firebase:firebase-analytics-ktx’

Go back to the console and go to the General tab in project settings:

Under your apps, you can then add an app, which will prompt you to do these steps:

Once this is done, you should be able to access a file called google-services.json, that will need to be put in your app directory.

Registering for Push Notifications

In your Application class, you’ll need to add the following line to the onCreate method:

FirebaseApp.initializeApp(this);

Then, to get the token (which is used in the API defined above):

public void FireBaseTokenGenerator(){
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> {
if (!task.isSuccessful()) {
Log.w("TAG", "Fetching FCM registration token failed", task.getException());
return;
}

// Get the registration token
token = task.getResult();

// TODO: Send this token to your REST API
 });
}

You can then send this token to your API and store it to use it when needed.

Receiving and Displaying Notifications

To handle notifications, you’ll need to create a service class extending FirebaseMessagingService

In this service, override the onMessageReceived(RemoteMessage remoteMessage) method. This will trigger each time you receive a push notification.

To retrieve the information you’ve sent with your api, you can use:

remoteMessage.getNotification().getTitle();

and

remoteMessage.getNotification().getBody();

To use this service, you can then register it in your manifest as follows:

And here you have it, you should now be able to set up Push notifications with your REST API and send custom notifications to the users when certain events are triggered.

If you have any questions feel free to ask them in the comments below or to contact us at :

lizardanddog.com



This post first appeared on Lizard And Dog Blog - Mobile And General Programming Tutorials, please read the originial post: here

Share the post

Setting up Firebase Push notifications with a REST API

×

Subscribe to Lizard And Dog Blog - Mobile And General Programming Tutorials

Get updates delivered right to your inbox!

Thank you for your subscription

×