HTTPoison fetching

so I need to use the HTTPoison library to fetch the url https://jsonplaceholder.typicode.com/todos/1 and print out the todo title on the console
My code is not running dont know where my error could be coming from .Here is my code:

def get_todos do
   todos = HTTPoison.get!("https://jsonplaceholder.typicode.com/todos/1")
   todo = todos.body.map { todo, todo.to_s.sub() }
   Enum.each todo, fn todo ->
   IO.puts todo
end

(note: I edited your post to include triple-backticks ``` to format the code)

First off: if you’re getting an error, please share it when posting a question. In this case it’s relatively straightforward to run the code manually and see what happens, but in general readers can’t see what you’re seeing. (for instance, what if that URL was to a server that wasn’t publicly-accesible?)

The error I get when attempting to run the above code is:

iex(api@localhost)2> todo = todos.body.map { todo, todo.to_s.sub() } 
** (CompileError) iex:2: undefined function todo/0 (there is no such import)

Not the error, but calling functions with . (like todos.body.map above) is much less common in Elixir than say, Ruby. You’d want something like Enum.map(todos.body) instead - but see below, because that will give you an error too.

The immediate compile error here would be silenced by using Enum.map:

todo = Enum.map(todos.body, fn todo -> ... do something with todo .... end)

but that won’t actually work, since todos.body is a string:

"{\n  \"userId\": 1,\n  \"id\": 1,\n  \"title\": \"delectus aut autem\",\n  \"completed\": false\n}"

You could pass that to Jason.decode!/1 or similar to get a map:

Jason.decode!(todos.body)
# result:
%{
  "completed" => false,
  "id" => 1,
  "title" => "delectus aut autem",
  "userId" => 1
}

For this endpoint, you likely don’t want to use Enum.map at all - there aren’t multiple results to iterate over.

1 Like