Njord

Njörðr, god of the wind and the sea.

Build StatusHex pmhex.pm downloads

This library is a wrapper over HTTPoison to build client APIs. It provides a series of macros that make easy to write a REST API client specification while generating the corresponding functions of the API. Relies on HTTPoison to do the actual request. To define a custom API specification just use Njord.Api module as base.

defmodule Github do
  use Njord.Api
  alias Njord.Api.Request, as: Request

  @url "https://api.github.com"

  def process_url(request, path, _state) do
    %Request{request | url: @url <> path}
  end

  defget :get_repos,
    path: "/users/:username",
    args: [:username]
end

The above example shows how to create the functions get_repos/1 and get_repos/2 (this one receives a list of options for HTTPoison or any of the options for the endpoint metioned later in this document) for the endpoint GET https://api.github.com/users/:username.

For synchronous requests:

iex(1)> alias HTTPoison.Response, as: Response
iex(2)> Github.get_repos("alexdesousa")
{:ok, %HTTPoison.Response{...}}

For asynchronous requests:

iex(3)> Github.get_repos("alexdesousa", stream_to: self())
{:ok, %HTTPoison.AsyncResponse{...}}
iex(4)> flush
%HTTPoison.AsyncStatus{...}
%HTTPoison.AsyncHeaders{...}
%HTTPoison.AsyncChunk{...}
...
%HTTPoison.AsyncChunk{...}
%HTTPoison.AsyncEnd{...}

Overriding functions

Like HTTPoison, Njord.Api defines the following list of functions, all of which can be overriden:

# Processes the endpoint URL after the substitutions.
@spec process_url(Njord.Api.Request.t, String.t, term) :: Njord.Api.Request.t
def process_url(request, url, state)

# Processes the request headers.
@spec process_headers(Njord.Api.Request.t, [{binary, binary}], term) :: Njord.Api.Request.t
def process_headers(request, headers, state)

# Processes the request body.
@spec process_body(Njord.Api.Request.t, term, term) :: Njord.Api.Request.t
def process_body(request, body, state)
      
# Processes the response headers.
@spec process_response_headers(HTTPoison.Response.t, [{binary, binary}], term) :: HTTPoison.Response.t
def process_response_headers(response, headers, state)

# Processes the response body.
@spec process_response_body(HTTPoison.Response.t, String.t, term) :: HTTPoison.Response.t
def process_response_body(response, body, state)

# Processes the status code of the request.
@spec process_status_code(HTTPoison.Response.t, int, term) :: HTTPoison.Response.t
def process_status_code(response, status_code, state)

These functions are executed in the order they were listed.

Options

When generating the specification of the endpoint, there are several options:

And when calling the genererated function there are other aditional options:

Installation

  def deps do
    [{:njord, "~> 0.1.1"}]
  end
  def deps do
    [{:njord, github: "gmtprime/njord"}]
  end
  def application do
    [applications: [:httpoison]]
  end