Skip to content

OneSignalDevelopers/OneSignal-REST-API-Push-Sample

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OneSignal REST API Push Sample

Maintenance Twitter: onesignaldevelopers

This sample NodeJS app demonstrates how to send push notifications to your app using the OneSignal REST API.

This project was generated with NodeJS version v14.16.0

Take a look at the OneSignal documentation to learn how to integrate OneSignal into your project. After you have integrated OneSignal into your application, you can use NodeJS to send push notification using the OneSignal REST API.

Development server

  • Install project dependencie by running npm i (npm install).

  • Run npm run start for a dev server. The app will automatically run the createNotication() which will make a call to our API to create a notficationwhich will be sent to your app.

Options Builder

This is a helper function created for this code sample. This helper function generates an options object containing the information need it to make the API call. Below you can find a sample object generated after running the optionsBuilder(method, path, body) function. This function was created for reusability purposes, no need to have this function to run the OneSignal REST API, all you need is an options object.

{
    method: 'POST',
    url: 'https://onesignal.com/api/v1/notifications',
    headers: {
        'Content-Type': 'application/json',
        Authorization: 'Basic API_KEY'
    },
    body: {
      app_id:'API_ID',
      included_segments:['Subscribed Users'],
      data:{foo:'bar'},
      contents:{en:'Sample Push Message'}
    }
}

Create Notification

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

const createNotication = (body) => {
    const options = optionsBuilder("POST","notifications", body);
    request(options, (error, response) => {
        if (error) throw new Error(error);
        console.log(response.body);
        viewNotifcation(JSON.parse(response.body).id);
    });
}

View Notification

View the details from a push notification you have sent using OneSignal.

const viewNotifcation = (notificationId) => {

    const path = `notifications/${notificationId}?app_id=${ONESIGNAL_APP_ID}`;
    const options = optionsBuilder("GET", path);
    request(options, (error, response)=> {
        if (error) throw new Error(error);
        console.log(response.body);
    });
}

Show Your Support

Give a ⭐️ if this project helped you!

Join the OneSignal Developers Community

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.