Building an Ad-hoc HTTP Server

Get familiarized with the approach of building an ad-hoc HTTP server.

We'll cover the following...

Let’s go back to the weather API use case.

Press + to interact
#file path -> soggy_waffle/lib/soggy_waffle/weather_api.ex
@behavior SoggyWaffle.WeatherAPI.Behavior
@spec get_forecast(String.t()) ::
{:ok, map()} | {:error, reason :: term()}
def get_forecast(city) when is_binary(city) do
app_id = SoggyWaffle.api_key()
query_params = URI.encode_query(%{"q" => city, "APPID" => app_id})
url =
"https://api.openweathermap.org/data/2.5/forecast?" <> query_params
case HTTPoison.get(url) do
{:ok, %HTTPoison.Response{status_code: 200} = response} ->
{:ok, Jason.decode!(response.body)}
{:ok, %HTTPoison.Response{status_code: status_code}} ->
{:error, {:status, status_code}}
{:error, reason} ->
{:error, reason}
end
end

The weather API exposes a GET /data/2.5/forecast endpoint that we hit from our application. This endpoint accepts two parameters in the query string:

  • Parameter q represents the query.
  • APPID, which identifies the credentials of our application.

The endpoint returns a 200 OK HTTP response with a JSON body containing information ...