Last active
July 7, 2020 03:53
-
-
Save arosenb2/8e6d84f6ab9b462b6f9f62fce8532de3 to your computer and use it in GitHub Desktop.
OpenWeatherMap API Basic Integration using Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Weather do | |
@moduledoc """ | |
deps: [ | |
{:poison, "~> 4.0"}, | |
{:httpoison, "~> 1.7"} | |
] | |
""" | |
@api_key "" # obtain for free at https://openweathermap.org/api | |
@base_url "https://api.openweathermap.org/data/2.5" | |
# Default coordinates of Atlanta, GA | |
@default_latitude "33.7490" | |
@default_longitude "-84.3880" | |
defp prefix(str, prefix) do | |
String.replace_prefix(str, "", prefix) | |
end | |
defp prefix(str, prefix, predicate) do | |
cond do | |
predicate.(str) -> prefix(str, prefix) | |
true -> str | |
end | |
end | |
defp map_to_params, do: "" | |
defp map_to_params(map) do | |
map | |
|> Enum.map(fn {k, v} -> Atom.to_string(k) <> "=" <> v end) | |
|> Enum.join("&") | |
|> prefix("?", fn str -> byte_size(str) > 0 end) | |
end | |
def fetch(latitude \\ @default_latitude, longitude \\ @default_longitude) do | |
%{ | |
lat: latitude, | |
lon: longitude, | |
units: "imperial", | |
appid: @api_key | |
} | |
|> map_to_params() | |
|> prefix(@base_url <> "/weather") | |
|> HTTPoison.get! | |
|> Map.get(:body) | |
|> Poison.decode!(keys: :atoms) | |
end | |
def pretty_print(forecast) do | |
with %{name: name, main: %{ temp: temperature, humidity: humidity }} = forecast, | |
temp = Float.floor(temperature, 0) |> trunc() |> Integer.to_string() do | |
"Currently in " <> name <> ", it is " <> temp <> "˚F, with a humidity of " <> Integer.to_string(humidity) <> "%." | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment