DEV Community

Alex Spinov
Alex Spinov

Posted on

Ky Has a Free API — Here's How to Use This Tiny HTTP Client

Ky is a tiny and elegant HTTP client built on the Fetch API. At just ~3KB, it provides retry logic, timeout handling, hooks, and JSON shortcuts that the native fetch lacks.

Installation

npm install ky
Enter fullscreen mode Exit fullscreen mode

Basic Usage

import ky from "ky";

// Simple GET with automatic JSON parsing
const data = await ky.get("https://api.github.com/users/sindresorhus").json();
console.log(data.name); // Sindre Sorhus

// POST with JSON body
const response = await ky.post("https://httpbin.org/post", {
  json: { name: "Ky", type: "http-client" }
}).json();
Enter fullscreen mode Exit fullscreen mode

Retry and Timeout

// Auto-retry on network errors and 5xx responses
const api = ky.create({
  prefixUrl: "https://api.example.com",
  retry: { limit: 3, methods: ["get"], statusCodes: [408, 502, 503, 504] },
  timeout: 10000,
  headers: { "Authorization": "Bearer token" }
});

const users = await api.get("users").json();
Enter fullscreen mode Exit fullscreen mode

Hooks — Intercept Requests and Responses

const api = ky.create({
  hooks: {
    beforeRequest: [
      (request) => {
        request.headers.set("X-Request-ID", crypto.randomUUID());
      }
    ],
    afterResponse: [
      async (request, options, response) => {
        if (response.status === 401) {
          const token = await refreshToken();
          request.headers.set("Authorization", `Bearer ${token}`);
          return ky(request);
        }
      }
    ]
  }
});
Enter fullscreen mode Exit fullscreen mode

Search Params

const data = await ky.get("https://api.example.com/search", {
  searchParams: { q: "web scraping", page: 1, limit: 20 }
}).json();
Enter fullscreen mode Exit fullscreen mode

Why Ky Over Fetch?

  • Automatic retries on network errors
  • Timeout support (fetch has none by default)
  • JSON shortcuts (.json() method, json option for body)
  • Hooks for request/response interception
  • Tiny bundle — ~3KB gzipped

Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)