2
votes

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?

2

2 Answers

4
votes

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)
1
votes

You might have an easier time getting it working and understanding it from outside Phoenix first. As Mike pointed out, HTTPoison is the standard library to use for the task.

To do that, you need to...

  1. add HTTPoison as a dependency in your mix file
  2. run mix deps.get
  3. call it from inside your project
  4. Parse the response, probably with a JSON decoding library like Poison

Here's a video that takes you through putting HTTPoison into an empty project, making API calls (and decoding the responses) from the iex interactive shell and then from inside your project (which is an OTP app you can toss into your Phoenix app if you want).