/apidly

Node and Browser API module.

Primary LanguageTypeScriptOtherNOASSERTION

APIDLY

NodeJS and Browser API client. In order to use with NodeJS please pick you favorite Fetch API polyfill library like cross-fetch.

Build Status NPM version Downloads Coverage Status Maintainability Snyk

Table of Contents

Features

  • Uses Fetch API (requires fetch polyfill for NodeJS)
  • Automatic transforms for JSON/Form data. Also, supports any custom data transformation
  • TypeScript support
  • Retry mechanism
  • Request and Response middlewares

Browser Support

Chrome Firefox Safari Opera Edge
Latest ✔ Latest ✔ Latest ✔ Latest ✔ Latest ✔

Installing

Using yarn:

$ yarn add apidly

Using npm:

$ npm install apidly

Examples

Simple Example

import 'cross-fetch/polyfill';
import { createClient, createEndpoint } from 'apidly';

const client = createClient({ base: 'https://api.example.com' });

interface Post {
  id: string;
  title: string;
  content: string;
}

const postsListEndpoint = createEndpoint<Post[]>('/api/v1/posts');

export const listPosts = () => client(postsListEndpoint);

Advanced Example

import { createClient, createEndpoint, formRequest, ApidlyRequest } from '../index';
import { getAccessToken } from './authorization';

const client = createClient({
  base: 'https://api.example.com',
  headers: { locale: 'en_US' },     // default client's headers
  requestType: formRequest,         // use form-urlencoded request type
  maxRetries: 3,                    // additional retries count
}).request(async (url: URL, request: ApidlyRequest) => {
  // custom request middleware with authentication
  const token = await getAccessToken();
  request.headers.set('authorization', `Bearer ${token}`);
});

interface Post {
  id: string;
  title: string;
  content: string;
}

interface UpdatePostParams {
  id: string;
}

interface UpdatePostData {
  title: string;
  content: string;
}

const postsUpdateEndpoint = createEndpoint<Post, UpdatePostParams, UpdatePostData>('/api/v1/posts/{id}', { method: 'put' });

export function updatePost(id: string, post: UpdatePostData) {
  return client(postsUpdateEndpoint, { params: { id }, data: post });
}

License

License Apache-2.0 Copyright (c) 2021-present Ivan Zakharchanka