DEV Community

Cover image for How to write the right API client in TypeScript

How to write the right API client in TypeScript

Matvey Romanov on June 17, 2023

In this article, I will talk in detail about the implementation of the client API in TypeScript for working with both third-party APIs and my own. ...
Collapse
 
kbirgerdev profile image
Kirill Birger

This is pretty good, and I think you're on the right track, but it could be improved in a few ways.

  1. You don't need to create so many instances. You're in JS which is single threaded. Your code is mostly stateless.

  2. Use unknown instead of any. It saves mistakes later, and communicates your intent better to the caller.

  3. Abstract more. The caller of your code should know nothing of HTTP. You stated that a goal was to avoid change if your API changes. That's a good goal.

Collapse
 
ra1nbow1 profile image
Matvey Romanov

Thanks

Collapse
 
joshkarp profile image
Joshua Karp

Curious about the abstraction part? I may be missing it but how does the caller know anything of the HTTP?

Collapse
 
cowedeveloper profile image
Muhammad Owais

Do you have a video of this? As a newbie i hardly able to catch that.

Collapse
 
raibtoffoletto profile image
Raí B. Toffoletto

This ia a bit over engineered, isn't it!? It's easier and cleaner to use native es modules over classes. Then, there's no need to have a createClient in all methods, just important the axios instance. 😉

Collapse
 
ra1nbow1 profile image
Matvey Romanov • Edited

It's an irregular approach :)

Collapse
 
raibtoffoletto profile image
Raí B. Toffoletto

Irregular!? Are you sure!? 🙃

Thread Thread
 
ra1nbow1 profile image
Matvey Romanov

I mean my approach that I've shown in this article

Collapse
 
joshkarp profile image
Joshua Karp

Great article.

Collapse
 
ra1nbow1 profile image
Matvey Romanov

Thank you

Collapse
 
nfroidure profile image
Nicolas Froidure

I'd recommend not to write an API client but instead generate it. I wrote this github.com/nfroidure/openapi-ts-sd... for generating a SDK from OpenAPI, it is still highly customizable but It avoids repeating myself.

I agree with other comments to avoid classes too.

Collapse
 
ra1nbow1 profile image
Matvey Romanov

This is really a good alternative

Collapse
 
raphydev profile image
Raphael Blehoue

Great Article Sir

Collapse
 
ra1nbow1 profile image
Matvey Romanov

Thanks a lot