Onesignal in an awesome platform for sending push notifications to your mobile and web apps. They provide a feature-rich REST API for programmatically sending notifications from your server to their endpoints very easily. You can read the nitty-gritty details of the API at https://documentation.onesignal.com/reference.

In this tutorial, I will show you how to use onesignal with HTTPoison, a HTTP client for Elixir. I assume that you already have a project created with Phoenix Framework.

First, add HTTPoison to the mix.exs file inside your project folder

def deps do
  [{:httpoison, "~> 0.10.0"}]
end

After that run mix deps.get in your terminal to fetch the dependency and also make sure to add :httpoison as an application dependency

def application do
  [applications: [:httpoison]]
end

You can use the following code to send a notification to all subscribers. Please don’t forget to replace REST-API-KEY-HERE and YOUR-APP-ID-HERE with your actual credentials. It’s not recommended to hard code sensitive details like this here. In the Phoenix Framework, API keys like this can be stored at config/prod.secret.exs and can be imported into the necessary files

headers = [
  {"Content-Type", "application/json; charset=utf-8"},
  {"Authorization", "Basic REST-API-KEY-HERE"}
]

body = %{
  "app_id" => "YOUR-APP-ID-HERE",
  "contents" => %{ "en"=> "Message Here" },
  "included_segments"=>["All"]
}

{:ok,body} = Poison.encode(body)

HTTPoison.post "https://onesignal.com/api/v1/notifications", body, headers

Here we use Poison.encode to convert the map to a JSON string