Initial commit.
This commit is contained in:
commit
005477d827
14 changed files with 274 additions and 0 deletions
37
lib/swapi_example.ex
Normal file
37
lib/swapi_example.ex
Normal file
|
@ -0,0 +1,37 @@
|
|||
defmodule SwapiExample do
|
||||
@moduledoc """
|
||||
Lists all of the starships and their respective pilots from the Star Wars
|
||||
API.
|
||||
"""
|
||||
|
||||
alias SwapiExample.Client
|
||||
|
||||
@doc """
|
||||
The main entrypoint of the program.
|
||||
"""
|
||||
def run do
|
||||
IO.puts("Starship Model\t| Starship Name\t| Pilots")
|
||||
{:ok, resp} = Client.starships()
|
||||
|
||||
print_starships(resp)
|
||||
end
|
||||
|
||||
defp print_starships(resp) do
|
||||
starships = resp.body["results"]
|
||||
|
||||
for starship <- starships do
|
||||
pilots = for pilot_url <- starship["pilots"] do
|
||||
{:ok, resp} = Client.get(pilot_url)
|
||||
pilot = resp.body
|
||||
pilot["name"]
|
||||
end
|
||||
|
||||
IO.puts("#{starship["model"]}\t| #{starship["name"]}\t| " <> Enum.join(pilots, ", "))
|
||||
end
|
||||
|
||||
if resp.body["next"] do
|
||||
{:ok, next_resp} = Client.get(resp.body["next"])
|
||||
print_starships(next_resp)
|
||||
end
|
||||
end
|
||||
end
|
19
lib/swapi_example/client.ex
Normal file
19
lib/swapi_example/client.ex
Normal file
|
@ -0,0 +1,19 @@
|
|||
defmodule SwapiExample.Client do
|
||||
use Tesla
|
||||
|
||||
plug Tesla.Middleware.BaseUrl, "https://swapi.dev/api/"
|
||||
plug Tesla.Middleware.FollowRedirects
|
||||
plug Tesla.Middleware.JSON
|
||||
|
||||
def starships() do
|
||||
get("/starships/")
|
||||
end
|
||||
|
||||
def people() do
|
||||
get("/people/")
|
||||
end
|
||||
|
||||
def person(id) do
|
||||
get("/people/#{id}/")
|
||||
end
|
||||
end
|
Loading…
Add table
Add a link
Reference in a new issue