DEV Community

Writing type safe API clients in TypeScript

Nazeel on January 06, 2024

Writing API integrations can be a daunting task. But it does not need to be. How many times have you had to deal with these problems? You want ty...
Collapse
 
manchicken profile image
Mike Stemle

I'd recommend looking at the Fetch API, as the axios module is not a standardized interface and will result in larger running programs.

Also, can you help me understand how type-safety comes into play here in a way that can't be boiled down to simple validation? From what I gather of your article, ajv with a JSON schema would be just as "type-safe" since TypeScript doesn't actually affect types or type-safety under the hood.

Collapse
 
nazeelashraf profile image
Nazeel

Totally agree that the Fetch API is definitely the lightweight approach here, but unfortunately it does not support generics out of the box. This means instead of typing the response types at the api.ts level, we now have to type it inline at the response.json() as GetPetsResponse, which can be cumbersome if the same API call is used in different places. For more information, please see this GitHub thread. To circumvent this, we may have to write a custom wrapper around fetch to achieve generics.

Regarding ajv, I am not familiar with the library, but from a quick glance, it looks like something that would require manually typing (please correct me if I'm wrong) and also, it needs to be added as a dependency. The issue with this is that we would be technically be creating two sources of of truth for the API Schema, which could possibly backfire in the long run. It also seems to be doing runtime validations, but in this article, we shift left the type safety into the dev/coding phase, assuming that the OpenAPI spec is the single source of truth, and if APIs are versioned correctly (ie, v1, v2, etc), we wouldn't need to go back and change the schema very often. However, I can see the flexibility it provides on the server side with custom validation when we expect APIs, which are likely external, to return malformed values. For internal APIs though, we should be able to get away with the approach mentioned in the article.

Thanks for the comment, I hope I was able to answer it!

Collapse
 
harsh2909 profile image
Harsh Agarwal

This is a great tool for generating TypeScript based Types.
You might wanna check out kiota by Microsoft.
github.com/microsoft/kiota

This will allow you to generate API clients for most of the common languages.

Collapse
 
nazeelashraf profile image
Nazeel • Edited

Although it seems like you need to add deps, which openapi-typescript does not need since we use npx, this looks super cool and I'll definitely be checking it out. Thanks for pointing it out!

Collapse
 
robinamirbahar profile image
Robina

Nice