Thibault Maekelbergh

🌚 REST JSON to Typescript with Insomnia

What is going wrong?

In my ideal world we use GraphQL apis that auto document themselves based on their schema and generate Typescript types with graphql-codegen.

However we don't live in my ideal world and the second best option is that we use OpenAPI specs that are well documented and which we can maybe derive TS types from via a tool like openapi-typscript.

Unfortunately there are a lot of cases were even that form of documentation is lacking. If you are reverse-engineering a public API or using APIs written by single open source contributors, then chances are pretty low that you are going to get an OpenAPI spec.

Insomnia

I love Insomnia, mainly because I hate Postman. The latter is super cluttered, doesn't look modern, is slow and has way too many buttons. Insomnia is lightweight and focuses on what matters.

Currently I'm working with a OneTrust API which has a huge JSON body that's being returned. I need those in my codebase but didn't want to manually type or copy over and adapt all the fields in the response.

Large JSON body returned by the OneTrust API. Some fields are redacted because they are for my eyes only!

A quick internet roundtrip enlightened me with a cool trick, you can use an Insomnia plugin to generate TS types based on the response body.

Install the insomnia-plugin-res2ts plugin by entering its name in Insomnia's plugin prefs and clicking "Install Plugin":

Insomnia's Plugin preference view

That's it! Now execute the call once, right-click the call in the sidebar to select "Generate Typescript Types", and then save the file as types.ts to a location on your computer.

Auto-generated TS types. Sweet 🐍.

Typescript types generated by Insomnia