Hey, guys! How are you?
I’m doing a challenge from a course about programming and choose to do it using Elixir since I want to learn how to create APIs using Phoenix…
I need to loop over 5 pages that return me a json with a bunch of numbers on each page, put them inside a json of my own with all the numbers ordered, that part I got already
But the problem is, there is catch in this challenge, sometimes the external API server will throw me a status 500 on purpose. How would I retry the same request that I did if I get back a status 500?
For now the part where I make the request is like this
def get_numbers(page) do
"#{@base_url}#{page}"
|> get()
|> handle_get()
end
defp handle_get({:ok, %Tesla.Env{status: 200, body: body}}), do: {:ok, body}
defp handle_get({:ok, %Tesla.Env{status: 404}}), do: {:error, "Page not found!"}
defp handle_get({:ok, %Tesla.Env{status: 500}}), do: {:error, "Internal error"}
defp handle_get({:error, _reason} = error, _page), do: error
How would I retry the request if it hits my third handle_get until the status is 200 so it hits my first handle_get?
Also, I’m doing all the request recursively like this
def call() do
page = 1
page
|> recursive_call()
end
defp recursive_call(page) do
page
|> Client.get_numbers()
|> handle_response()
page = page + 1
if page <= 5 do
recursive_call(page)
end
end
defp handle_response({:ok, body}), do: {:ok, Number.build(body)}
defp handle_response({:error, _reason} = error), do: error
But I should be checking if the body that the api is returning my is empty, like with some pseudo code
If body == {“numbers”: []}:
stop recursion