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).
SummaryCLI 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
Enter fullscreen mode Exit fullscreen mode
Call an API with SDKYou 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);
})
Enter fullscreen mode Exit fullscreen mode
In case generated codes violate linter rules in your project, you need to configure the linter to ignore them.
# .eslintignore
src/client-axios
Enter fullscreen mode Exit fullscreen mode
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"]
}
}
Enter fullscreen mode Exit fullscreen mode
axiosDefine interface for response bodies and pass them as type parameters in axios API.
interface Todo {
userId: number,
id: number,
title: string,
completed: boolean,
}
Enter fullscreen mode Exit fullscreen mode
import axios from 'axios';
const url = 'https://jsonplaceholder.typicode.com/todos/1';
axios.get<Todo>(url).then((res) => {
console.log(res.data);
});
Enter fullscreen mode Exit fullscreen mode
ReferenceRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4