18
votes

I'm a Ruby dev trying to get into elixir. I'm trying to interact with an API in order to learn a little Elixir. I'm basically trying to make an http request. In ruby the thing I'm trying to do would look like this.

require 'httparty'


url = "https://api.sportradar.us/nba/trial/v4/en/games/2016/11/05/schedule.json?api_key={api_key}"
response = HTTParty.get(url)
req = response.parsed_response

Pretty straightforward and simple. Now I have a json decoded response that I can use. How can I do this with Elixir and Phoenix?

2
Have you tried searching for a library? github.com/edgurgel/httpoison is the most popular one. With that, HTTPoison.get(url) should fetch the data.Dogbert
Yea, I just found that. It looks great.Bitwise
You can also look at github.com/myfreeweb/httpotion, if intereseted on knowing the difference and probably why you would not use them read this interesting article virviil.github.io/2018/04/06/…Sigu Magwa

2 Answers

24
votes

With httpoison (HTTP Client) and poison (JSON Encoder/Decoder) packages, this is almost as simple as your code which uses HTTParty:

url = "https://api.sportradar.us/nba/trial/v4/en/games/2016/11/05/schedule.json?api_key=#{api_key}"

response = HTTPoison.get!(url)
req = Poison.decode!(response.body)
17
votes

Not only can you write your code as simply as before as shown in @Dogbert's example, but you can do cool things with pattern matching, too (and be as granular as you like)

Using HTTPoison and Poison, as well:

url = "https://api.sportradar.us/nba/trial/v4/en/games/2016/11/05/schedule.json?api_key={api_key}"

case HTTPoison.get(url) do
  {:ok, %{status_code: 200, body: body}} ->
    Poison.decode!(body)

  {:ok, %{status_code: 404}} ->
    # do something with a 404

  {:error, %{reason: reason}} ->
    # do something with an error
end