How to Send Push Notifications with the OneSignal REST API
Tags: node, webdev, mobiledev, api
Published: 2022-05-06 06:39:51

---
title: How to Send Push Notifications with the OneSignal REST API
published: true
date: 2022-04-18 13:00:00 UTC
tags: nodejs, webdev, mobiledev, api
canonical_url: https://onesignal.com/blog/how-to-send-push-notifications-with-the-onesignal-rest-api/
---

 ![How to Send Push Notifications with the OneSignal REST API](https://onesignal.com/blog/content/images/2022/04/send-push-notifications-with-the-onesignal-rest-api.jpg)

It’s no secret that push notifications can help you engage and retain app users. In this tutorial, we'll show you how to use the [OneSignal REST API](https://documentation.onesignal.com/reference/create-notification) using NodeJS.  
  
Using the OneSignal REST API is very useful because it can help you integrate OneSignal into different workflows that your applications may have. The OneSignal REST API is friendly with different technologies including front and backend. Basically, if the tech stack you are using supers API calls, then you can use the OneSignal REST API.

### OneSignal & Your Browser's Push API

The Push API gives applications the ability to receive messages from a server whether or not the app is in the foreground or currently loaded on a user agent. This lets you deliver asynchronous notifications and updates to users who opt-in, resulting in better engagement with timely new content.

This tutorial will cover an overview of our OneSignal REST API reference and the usage of our API with a NodeJS server.

### Guide Overview

- **Part 1: OneSignal REST API Overview**
- REST API reference
- **Part 2: Push Notification In NodeJS**
- Setup a NodeJS Application
- Send Push Notifications
- View Notification insights

This tutorial requires some basic knowledge of NodeJS and usage of REST APIs. Below is a list of platforms that I'm using:

- App with OneSignal integrated (mobile, web, or game)
- NPM
- I’m using NPM version v6.14.11
- NodeJS
- I’m using NodeJS v16.14.2

## Part 1: OneSignal REST API Overview

### Send Notifications

The OneSignal Push API allows you to programmatically send [push notifications](https://documentation.onesignal.com/reference/create-notification). The push notifications can be sent to different [segments](https://documentation.onesignal.com/reference/create-notification#send-to-segments) (by default you send them to all _**Subscribed Users)**_ and even specific devices using the User ID. Another cool feature of the OneSignal REST API is the ability to [cancel](https://documentation.onesignal.com/reference/cancel-notification) notifications that have been scheduled.

### View Notification

One of my favorite endpoints to use with the OneSignal REST API is the [view notification](https://documentation.onesignal.com/reference/view-notification) endpoint. This endpoint allows you to gather information about the notifications and outcomes associated with them. For example, the returned data can tell you see the number of notifications that have not been sent out, the number of notifications that got delivered, the number of confirmed deliveries, and much more information. If you want to learn more about all the [data returned](https://documentation.onesignal.com/reference/view-notification#returned-fields) by this endpoint visit our rest API reference.

**Method:** POST

**Endpoint:** [`https://onesignal.com/api/v1/notifications`](https://onesignal.com/api/v1/notifications)

Our API can do a lot more than just send a notification and view data from that notification. If you want to learn more about our whole REST API, visit the [OneSignal REST API overview](https://documentation.onesignal.com/docs/onesignal-api) page.

### Creating Your NodeJS App

Inside your terminal run the following commands to create a new NodeJS project using NPM:

```
npm init
```

After entering the previous npm command, answer all the questions that will appear on your terminal. These questions will generate the values of your `package.json`.

**Your package.json file will look like similar to this:**

```
{
    "name": "myapp",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    “type”: “module”
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC"
}
```

# **Setup your NodeJS App**

The first thing you need to do is to create an `index.js` file. This file will contain all code necessary to send and view your notifications.

At the top of this file, add the request npm package. This package will help us make API calls to the OneSignal endpoints in an easier way than doing it with NodeJS natively.

```
import axios from 'axios';
```

Now, run `npm install axios` to add the `axios` npm package into your project. After you have installed the `axios` NPM package, add the following three variables to your index.js after the `axios` import:

```
const API_KEY = "YOUR ONE SIGNAL API KEY";
const ONE_SIGNAL_APP_ID = "YOUR ONE SIGNAL APP ID";
const BASE_URL = "https://onesignal.com/api/v1";
```

To get the API KEY and the APP ID from OneSignal, navigate to the OneSignal Dashboard and click on the app you created inside of OneSignal. Once you have selected the app you want to work with, click the **_S_** _ **ettings** _ tab.

![How to Send Push Notifications with the OneSignal REST API](https://lh4.googleusercontent.com/GmzXLp6PIMzhztSRsvfbm5vuDNzNOpc7NlRnMYtUMJ4frAvLNd_ZbY9NSdRj_rXFaFCI0Z5z1EOvi55Vd-CfoRaBi0jbA-8DSVQnBwnltWf_MsxpIovT48w3YmKdZNbdksnEJvxm)

On this page, click on **_Keys & IDs_**.

![How to Send Push Notifications with the OneSignal REST API](https://lh5.googleusercontent.com/UP60T5nA4EqhL35YXMayKUZoA9gq_qvtldUhLMNyMwOiz3npa7hXaoHi0ogiY7-EXheBV3yvfZRckMRtnVeojsVN6eCsx7QmStexn2FNChAR66G3ZyaaiCrxXof1LWG9b3a2yEX1)

Copy the **OneSignal App ID** and the **REST API KEY**.

![How to Send Push Notifications with the OneSignal REST API](https://lh4.googleusercontent.com/HYxlRKKp86qbNNhWML82Aw3ZgpuGRzTdrzcv1xHPjcghxVBt_U9OcXkRCMAECw9lGRGl-q3gsBMNu0I1NkRYIYC12AT7XSDKypK1nvNu3aYb0lLGgBqwx_MIE8PXPzofTZkY2inp)

**Note:** Another quick and easy way to access your OneSignal App ID is by copying it from the URL.

![How to Send Push Notifications with the OneSignal REST API](https://lh6.googleusercontent.com/ia4xoDWkmAj1D3DrklCJzCwcS7x3sxIJlUXS7MsDsMNdkDZ2urwfjz7lCt7GB2933dFi2aTUFydoi6HcdB7VQCrPaR1cg0q79dA4-_Xxi9lC1zS9g6SeOTwbJjYF_jasznHu09SS)

### Options Builder

This function is not mandatory in order to use the OneSignal REST API. This function will be in charge of creating the options that you will pass to your API calls. This is a generic function that will build the JSON object based on the parameters that you have passed.

**Parameters:**

- @param {string} method
- @param {string} path
- @param {object} body

**Returns:**

- @returns {object} options

```
const optionsBuilder = (method, path, body) => {
    return {
        method,
        'url': `${BASE_URL}/${path}`,
        'headers': {
        'Content-Type': 'application/json',
        'Authorization': `Basic ${API_KEY}`,
        },
        body: body ? JSON.stringify(body) : null
    };
}
```

### Create Notification

Create a push notification and send it to the users of your app.

**Method:** POST

**Endpoint:** [`https://onesignal.com/api/v1/notifications`](https://onesignal.com/api/v1/notifications)

### Postman Collection

To send a push notification, you will [add the following function that will make a call to the OneSignal REST API](https://www.postman.com/onesignaldevs/workspace/onesignal-api/request/16845437-c4f3498f-fd80-4304-a6c1-a3234b923f2c). This function takes a body parameter that represents the information that the push notification will contain.

**Parameters:**

- @param {object} body
- @returns {object} response

```
const createNotication = async (data) => {
const options = optionsBuilder("post","notifications", data);
try {
        const response = await axios(options);
        return response.data;
    } catch (error) {
        console.error(error);
        return error;
    }
}
```

Here’s a sample body object:

```
const body = {
    app_id: ONE_SIGNAL_APP_ID,
    included_segments: ['Subscribed Users'],
    data: {
    	foo: 'bar',
    },
    contents: {
    	en: 'Sample Push Message',
    },
};
```

### View Notification

Create a push notification and send it to the users of your app.

**Method:** GET

**Endpoint:** [`https://onesignal.com/api/v1/notifications`](https://onesignal.com/api/v1/notifications)

### Postman Collection

To send a push notification, you will [add the following function that will make a call to the OneSignal REST API](https://www.postman.com/onesignaldevs/workspace/onesignal-api/request/16845437-c4f3498f-fd80-4304-a6c1-a3234b923f2c). This function takes a body parameter that represents the information that the push notification will contain.

**Parameters:**

- @param {string} notificationId

```
const viewNotifcation = async (notificationId) => {
    const path = `notifications/${notificationId}?	app_id=${ONE_SIGNAL_APP_ID}`;
    	const options = optionsBuilder("get", path);
    try {
        const response = await axios(options);
        console.log(response.data);
    } catch (error) {
    	console.log(error);
    }
}
```

### Run Your Code

At the end of the file, add the following lines of code. The first `createNotification()` function will return the notification's basic information when you send push notifications. I’m using this function to call the OneSignal API. As you can see, I’m using object destructuring to grab the notification ID from the notification object returned from the `createNotification()`, that will be used to call the `viewNotifcation()` function.

```
const {id} = await createNotication(body);
await viewNotifcation(id);
```

Feel free to test other [OneSignal REST API](https://documentation.onesignal.com/reference/create-notification) endpoints and let us know what you think!

### Join the OneSignal Developers Community

Want to learn more about the OneSignal products and other technologies? Join our [OneSignal Developers Community](https://onesignal.com/onesignal-developers)!

The OneSignal Developer community is a group of passionate individuals who work with OneSignal products. Community members have the opportunity to expand their network and knowledge across different technologies.

### Stay Connected

Follow our [OneSignal Developers Twitter](https://twitter.com/OneSignalDevs) to learn more about the OneSignal product, technical tips, and the latest events from our developers.

The OneSignal Developer community gathers on our public chat server, available on Discord. [Our Discord server](https://discord.gg/EP7gf6Uz7G) is a safe environment to network with other members, ask questions, and learn from each other. It is also a place to engage with the OneSignal product development team.