Writing your first Elixir package (Part 2)

The real stuff

Syed Faraaz Ahmad
The Wheel
3 min readDec 8, 2017

--

In Part 1, we set up our project. Now we need to add functionality to it. Head back to IEX, now we’ll use the Tesla package to send an HTTP request to api.chucknorris.io/jokes/random, (make sure to include “https://” in the URL or Tesla will surely give you an error)

This weird syntax that it just returned is a Hash Map, that Elixir likes to call a Map. The API has returned a lot of information that we don’t need, like…AT ALL! The body part of the map seems like useful stuff, so we’ll take that:

Seems like we do have some useful output. This is essentially a JSON string, it can be converted into a JSON object by parsing it. Remember that Poison package? This is where it makes its entrance.

An epic entrance

Lets decode the JSON string to return a JSON object and use pattern matching to assign it to a variable:

Now if you check for result["value] :

Awesome! You finally have your Chuck Norris fact in a string form. Now, all that we have done above, lets put that into our random function

The |> is the pipe operator that basically takes the output of the previous function and executes the next function with that as its first argument. so basically:

Important note on publishing your packages

Although publishing a package to the hex repository is very easy, don’t publish it until you really solve a problem that you think a lot of people have. The cool thing about Elixir is that you don’t need to have it published on Hex, you can simply provide the Github link to your package repo and the package manager will gracefully oblige. So if you have a silly package like mine, try to refrain from publishing it.

That being said, here’s the awesome guide to prepping your package for publishing and then publishing on Hex.

If you would like to take a look at the other features I’ve provided in the package, head over here. Also check out the Github repo of this package if you think you can improve this package and contribute to it.

Happy Coding!

< Part 1

--

--

Syed Faraaz Ahmad
The Wheel

Software Engineer. I like to build cool things and write about them.