Getting images from the creative commons api

At the end of
https://guide.elm-lang.org/effects/random.html
there is an exercise about showing images instead of numbers.

I guess this can be solved similar to what is done in:
https://elm-lang.org/examples/cat-gifs
but then not looking for cats, but for dices?

So i tried using
https://api.creativecommons.engineering/v1/images?q=“dice%20one”&page_size=1
(which isn’t really fullproof, as the dice shown might be the wrong one, but i thought it was a nice idea)

This is the code i changed in https://elm-lang.org/examples/cat-gifs
to get the images, but this does not work unfortunately:

getRandomCatGif : Cmd Msg
getRandomCatGif =
  Http.get
    { url = "https://api.creativecommons.engineering/v1/images?q=%22dice%20one%22&page_size=1"
    , expect = Http.expectJson GotGif gifDecoder
    }


gifDecoder : Decoder String
gifDecoder =
  field "results" (index 1 (field "url" string)) 

As the results element is an array
Any suggestions,
(or also am i on the wrong trail in for this exercise?)

field "results" (index 1 (field "url" string)) 

Almost but Json.Decode.index starts at 0, try with index 0.


Note that you also have to expose index or use it qualified:

import Json.Decode exposing (Decoder, field, string, index)

or

import Json.Decode as Decode
...
Decode.field "results" (Decode.index 1 (Decode.field "url" Decode.string)) 

Thank you,
so whenever there is something alike

I cannot find a index variable:

120| field “results” (index 0 (field “url” string))
^^^^^
These names seem close though:

code
del
hidden
id

Hint: Read https://elm-lang.org/0.19.1/imports to see how import
declarations work in Elm.

Using the qualified name could be one the solutions.

As the examples in https://elm-lang.org/examples don’t seems to use qualified names often,
is qualified or unqualified import preferred?
Looking around: https://elmprogramming.com/easier-code-organization.html suggests using qualified imports.

Qualified names are usually preferable, see Should examples on package.elm-lang.org use qualified functions? for their use in examples and some references.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.