Deno.js Tutorial to Consume or Call REST JSON API Using node-kall Library in TypeScript Full Project For Beginners

 

Kall 🦜 Test

A small and intuitive wrapper around fetch for consuming REST+JSON-APIs. kall is compatible with Deno and Node.

It provides functions for each HTTP Method and an easy API to read their response, as well as handy constants for different status codes.

 

 

Installation

  • Deno: just use URL’s like in examples
  • Node: yarn add node-kall

 

 

Basic usage

import { get, OK } from "https://denopkg.com/olaven/kall@v1.0.8/mod.ts";

// Basic GET                   
const [status, todo] = await get("https://jsonplaceholder.typicode.com/todos/1");

console.log((status === OK) ?
    `Fetched Todo: ${todo}` :
    `${status} when fetching todo..`
);
//"node-kall" if using Node
import { get, OK } from "https://denopkg.com/olaven/kall@v1.0.8/mod.ts";

// Same as previous example, but with types
type Todo = { userId: number, id: number, title: string, completed: boolean }; //define the type the server is expected to return 
const [status, todo] = await get<Todo>("https://jsonplaceholder.typicode.com/todos/1"); // pass as generic 

console.log((status === OK) ?
    `Fetched Todo: ${todo}` :
    `${status} when fetching todo..`
);

Every function (getputpatchdelpost) returns the same format: [ status, body, response].

  • status: is the status code.
  • body: is the JSON-object the API returns (if any)
  • response: is the response fetch would have returned, for when you need it

Similarly, the last argument of any function (2nd for get and del, and 3rd for putpatch and post) takes a RequestInit-object, for when you need to pass custom headers etc.

In addition, kall provides utility functions for extracting only one of these, e.g.:

Name Example
filterStatus const status = await filterStatus(post('/api/todos', newTodo))
filterBody const body = await filterBody(put('/api/todos', updatedTodo))
filterResponse const response = await filterResponse(get('/api/todos'))

Leave a Reply