DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

Strongly-typed consuming of public API

I know it can be done in TypeScript + Node.js. Not sure about other programming languages (most common case seems to be Python?), or even Deno.

If you can get your hand on openapi.json (e.g. /v1/openapi.json), it is as simple as this post.

However, there is no openapi file, I prefer to write TypeScript interfaces with generic, and AxiosInstance; when the API is getting complex.

import axios, { AxiosInstance } from 'axios'
import rateLimit from 'axios-rate-limit'

export const api = rateLimit(
  axios.create({
    baseURL: process.env.API_BASE_URL,
    headers: {
      Authorization: `Bearer ${process.env.API_KEY}`,
    },
  }),
  /**
   * Requests per minute 60
   */
  {
    /**
     * Per second
     */
    maxRequests: 1,
    perMilliseconds: 1000,
  }
) as AxiosInstance
Enter fullscreen mode Exit fullscreen mode

Another important aspect is getting rate limited. Sending simultaneous 1000 API requests, and you will get a 429, Rate limit exceeded.

await Promise.all(
  Array.from({ length: 1000 }).map((_, i) => api.post(`/${i}`, { i }))
)
Enter fullscreen mode Exit fullscreen mode

So, what are other techniques you have tried, and possibly in other programming languages?

Top comments (0)