
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
1 | mix new joker |
Now open your mix.exs and then add these two libraries in deps function.
1 2 3 4 5 6 | defp deps do [ {:httpoison, "~> 1.0" }, {:json, "~> 1.0" } ] end |
1 2 3 4 5 | def application do [ extra_applications: [:logger, :httpoison] ] end |
Now let write some code, here am going to share the full code then I will explain every function in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | defmodule Joker do 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.
1 | 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
- 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
Reviewed by John Invictus
on
02:31
Rating:
