Popcornly gets all of its movie and TV data from The Movie Database (TMDB). At first I wrote the client by hand: a fetch call per endpoint and a TypeScript type per response. My git history from those weeks is a long list of commits like "Fixed more types", "Improved review type" and "Fixed external ids types".
Every one of those was me finding out that my type didn't match what the API actually returned.
The spec already existed
TMDB publishes an OpenAPI spec, a machine-readable description of every endpoint, parameter and response. Tools like Orval read a spec like that and generate the client: typed request functions and response types for every endpoint, in one command.
I rebuilt the package around that over a few days: generated code at the bottom, and a thin layer of hand-written services on top that group the functions the way an app actually uses them.
What changed
- Types stopped being guesses. They come from the same description the API is built from. A field I'd forgotten to make optional is optional, because the spec says so.
- New endpoints cost nothing. Adding page parameters to trending later was a regenerate, not an afternoon.
- I only own the part that's mine. The services layer is small, and it's where the decisions are: naming, grouping, which Next.js caching options to pass through.
Specs aren't perfect either
Generated code is only as good as the spec it reads. I had to fix a couple of spots in TMDB's spec where it didn't match reality, like the movie recommendations response, and later another type in it that needed correcting. So the package keeps its own slightly edited copy of the spec, checked in, and regenerates from that.
That turned out to be a better place for fixes anyway: a one-line change in the spec fixes the types and every function that uses them, instead of patching the same mistake by hand in three files.
What I took from it
- If an API publishes a spec, start from the spec. Hand-written types for someone else's API are a guess you have to keep re-checking.
- Generate the boring layer, and hand-write only the thin layer that expresses how you use the API.
- Keep the spec in the repo. It's documentation you can diff, and the place to fix the API's own mistakes.
