Prototyping a simple JSON API: best practices and gotchas

half this seems Elm related the other half seems Rest api related. perhaps better understanding REST will answer some. but one thing id like to note is, you’re not beholden to their api shape.

Lists like "isbn_13": ["9780140328721"] where it’s mostly a single entry (why not just use a String?

what I mean is in your model you don’t need to hold a List String
you could decode it as a single integer.
Decode.field "isbn_13" (Decode.index 0 Decode.int) (something like that)
and on your Model have an isbn : Int field.

the idea being you can transform the REST api data into whatever you want through decoders.
only decode the data you need and into the shape you need it in.

Having to build URLs for "covers": [8739161] with the covers api, rather than supplying a full url I can pull in.

that’s another api request to get the covers. chaining api reqs with Task.andThen is pretty common.

Having to use Json.Decode.maybe A LOT instead of Json.Decode.nullable, because they’re missing (and not null)

Decode.oneOf is sometimes nicer. you can try a decoder that has the required field, and if it doesn’t, then fall through to another decoder.

or you can make them optional and provide a default.

* It seems a lot of effort to build up a proper `Book` type in this way.

yep. that’s why tools like graphql exist. but idk if this book api supports it.

1 Like