Search code examples
elixirphoenix-framework

Call API Endpoint with Elixir/Phoenix


I have a trial of the sportradar API. I really don't care about sports but I'm trying to learn some Phoenix and Elixir. I'm trying to do something SUPER basic but can't seem to get it going. Basically, I'm trying to build up a URL with the given params and call an API endpoint. Get back the response and populate a view with what came back. Here is what I'm getting stuck on.

CONTROLLER

def index(conn, _params) do
  render(conn, "index.html")
end

def find_games(conn, params) do
  response = params["find_games"]["calender"]


end

I'm basically trying to say at this point call https://api.sportradar.us/nba/trial/v4/en/games/response["day]/response["month"]/response["year"]/schedule.json?api_key={api_key}

How do I make an http request with Elixir and Phoenix?


Solution

  • An example using HTTPoison.get:

    %{
      "day" => day,
      "month" => month,
      "year" => year
    } = response
    
    url = "https://api.sportradar.us/nba/trial/v4/en/games/#{day}/#{month}/#{year}/schedule.json"
    headers = []
    params = [api_key: api_key]
    
    {:ok, response} <- HTTPoison.get(url, headers, params: params)
    Poison.decode(response.body)