Elixir Working with Json API


In this post you will learn the following:
  • The best libraries to work with API JSON in elixir
  • How to decode and fetch data from the JSON response

For this tutorial am going to use JSON from this amazing website (http://www.icndb.com/api/) to fetch random funny jokes.I have used this API because it is somehow configurable to include your names.In case you want to use another service I highly recommend looking for one at this Github repo(https://github.com/toddmotto/public-apis).
Now lets create a new elixir project by writing the following on the terminal
mix new joker
The above command will create an elixir project called joker.
Now open your mix.exs and then add these two libraries in deps function.
  defp deps do
    [
      {:httpoison, "~> 1.0"},
      {:json, "~> 1.0"}
    ]
  end
After adding the above libraries download them to your project by typing mix deps.get on your terminal and also add :httpoison to your list of applications. ie
def application do
    [
      extra_applications: [:logger, :httpoison]
    ]
  end
:httpoison, will be used to fetch JSON data from the above API and then we will use :json to convert that JSON into an Elixir Map in order to access the items as key values. To learn more about these libraries visit their respective Github repositories.

Now let write some code, here am going to share the full code then I will explain every function in it.
defmodule Joker do
  @joke_server "http://api.icndb.com/jokes/random"

  def get_joke(your_name) do
    result =
      your_name
      |> split_name
      |> build_url
      |> fetch_decode_json

    case result do
      {:ok, joke} ->
        IO.puts(joke)

      :error ->
        IO.puts("An error occurred while fetching a random joke.")
    end
  end

  def split_name(name) do
    name
    |> String.split(" ")
    |> Enum.take(2)
  end

  def build_url([first, second | []]) do
    "#{@joke_server}?firstName=#{URI.encode(first)}&lastName=#{second}"
  end

  def build_url([first | []]) do
    "#{@joke_server}?firstName=#{URI.encode(first)}"
  end

  def fetch_decode_json(url) do
    url |> HTTPoison.get() |> decode_json
  end

  def decode_json({:ok, %HTTPoison.Response{body: body, status_code: 200}}) do
    case JSON.decode(body) do
      {:ok, json_map} ->
        joke = json_map |> get_in(["value", "joke"])
        {:ok, joke}

      _ ->
        :error
    end
  end

  def decode_json(_) do
    :error
  end
end


The main entry point of the above module is get_joke function, here you provide either your first name or both of your names. When you provide the name the text will be piped to split_name where the text is split into a list of words by String.split. If you just provide a single name, only one item will be stored in the list.
After the name is converted into a list of words we pipe it to build_url function where we use pattern matching to build an Url of the name depending or the number of names given.
Now let pipe the built url to fetch_decode_json where its content is fetched from the internet using HTTPoison.get(your_url), once the data is returned we use pattern matching to either return an :error atom or convert the JSON into a map that we can work with easily. The JSON will be converted into a map using the JSON.decode(your_json_here). To get the desired item from the nested map am using get_in function that is cleaner to use when compared to a method like this one.
joke = json_map["value"]["joke"]

After data is returned from fetch_decode_json, we use case function to match the results and return them to the console.

TIPS: when working with data in Elixir
  • Use iex -S mix, to run the functions you have written in order to know what data it was returned so that you can write the correct pattern to match it.
    ie
  • Use an editor with helper plugins to minimize errors.In my case am using Atom Editor
Exercise
  • Use this site to fetch and display data. https://jsonplaceholder.typicode.com/. If you experience any issue post it on the comment section bellow so that I can help.




If you like this article, consider buying me coffee.
Elixir Working with Json API Elixir Working with Json API Reviewed by John Invictus on 02:31 Rating: 5

No comments:

Powered by Blogger.