loading...

TypeScript REST API Client

unhurried profile image unhurried ・3 min read

In this article, I will introduce a list of REST API client libraries I've researched which can be used in TypeScript (browser or Node.js).

Summary

  • axios and typed-rest-client have many users and stable development activities.
    • As of Nov. 2019, axios is more popular than typed-rest-client. However, typed-rest-client might be going to get popularity in the future as it is maintained by Microsoft, that also maintains TypeScript.
  • Fetch API, which is a good option based on Web standard is not fully supported in all browsers, and some additional codes are required to support types.
    • Using Polyfill would solve the browser support problem.
  • Generating client SDK with OpenAPI Generator will save a lot when OpenAPI (Swagger) spec is available.

Examples of Using Libraries

OpenAPI Generator

Generate a Client SDK

CLI tool can be install in various ways such as NPM or Docker image. (cf. CLI Installation)

Generators that don't depend on a specific framework are the ones using axios or Fetch API. As I mentioned earlier, I chose typescript-axios. You can generate a client SDK in your src directory with the following command.

openapi-generator generate -g typescript-axios -i ./openapi.yaml -o ./src/client-axios
Call an API with SDK

You can change the base URL when a URL specified in OpenAPI document is different from the actual one.

import { DefaultApi } from '@/client-axios';

const baseUrl = 'https://jsonplaceholder.typicode.com';
new DefaultApi({ basePath: baseUrl }).getToDo(1).then((res) => {
  console.log(res.data);
})

In case generated codes violate linter rules in your project, you need to configure the linter to ignore them.

# .eslintignore
src/client-axios

Also, when your project uses webpack and configures the type definition to use only webpack-env, you need to add a type definitions of Node.js modules because generated codes use url module in Node.js. (cf. TypeScript Configuration Reference)

// tsconfig.json
{
  "compilerOptions": {
    "types": ["webpack-env", "node"]
  }
}

axios

Define interface for response bodies and pass them as type parameters in axios API.

interface Todo {
  userId: number,
  id: number,
  title: string,
  completed: boolean,
}
import axios from 'axios';

const url = 'https://jsonplaceholder.typicode.com/todos/1';
axios.get<Todo>(url).then((res) => {
  console.log(res.data);
});

Reference

Posted on by:

Discussion

markdown guide
 

Generating typings from openapi.yaml is a very good idea. Thanks for sharing.

For server-side, I have found an interface to JSON schema converter -- github.com/YousefED/typescript-jso... -- which is quite hand in creating OpenAPI (along with Fastify).

 

Does it work with Deno? It seems not to exist yet.