Writing and Publishing an Elixir Library
Recently, I wrote some code to query Google Books API, and extracted it into a Hex package. In this article, we will walk through the process of publishing an Elixir package to hex.pm.
Let’s start by generating a new project called
google_books using mix:
The files we will be working with are
which contains the
GoogleBooks module where we will write our code.
Since we’re working with an API,
we will need to depend on other libraries for HTTP requests and JSON parsing.
poison libraries in mix.exs,
by editing the
Writing the code
Our library will have just one module,
which provides the
This will be the code for our initial version of the package:
This is a simple module, so we won’t walk through the code itself, and instead focus on publishing the package to Hex. You can find the latest version of the source code on Github at nithinbekal/google_books.ex.
Adding package metadata
Before we publish the package to Hex, we need to add a description and package metadata for the package. Make the following changes to the mix file.
Registering on Hex
You can register as a user on Hex by using the
mix hex.user register command.
Skip this part if you already have registered a hex.pm account.
You will be prompted to enter username, email and password. A confirmation email will be sent to you, and you need to click on the confirmation URL before continuing.
Publishing the package to Hex
Finally, we’re ready to publish the package on Hex.
We can do this using the
mix hex.publish command.
Now the package is available at https://hex.pm/packages/google_books. Before we wind up, we need to add one final piece to our package - documentation.
First, let’s add
as development dependencies in the mix.exs deps list.
ExDoc lets you generate documentation for your project.
Earmark markdown parser that ExDoc depends on to parse inline documentation.
Next, let’s add some documentation for the
@moduledoc module attribute.
We will also add documentation to the
find_by_isbn/1 like this:
Now generate the docs by using
You can also push the docs to https://hexdocs.pm
by using the
mix hex.docs command.
You might also want some other files, like README, included as part of the generated docs. To do this, add this line to include README file in the docs:
If you generate the docs again, you will see the README file in the docs.
That’s all we will cover in this post. As you can see, it’s very easy to package your Elixir code into a hex package. If you’ve followed this tutorial to extract out libraries, I’d love to hear about them - please do leave a comment here.