DEV Community

Alex Spinov
Alex Spinov

Posted on

Ky Has a Free API That Makes HTTP Requests in JavaScript Elegant

Ky is a tiny HTTP client by Sindre Sorhus. It wraps fetch with retries, timeouts, hooks, and JSON handling — in just 3KB.

Basic Usage

import ky from "ky";

// GET with JSON parsing
const data = await ky.get("https://api.example.com/products").json();

// POST
const created = await ky.post("https://api.example.com/products", {
  json: { title: "Widget", price: 29.99 },
}).json();

// PUT, PATCH, DELETE
await ky.put("https://api.example.com/products/1", { json: { price: 24.99 } });
await ky.delete("https://api.example.com/products/1");
Enter fullscreen mode Exit fullscreen mode

Retry: Built-In Resilience

const data = await ky.get("https://api.example.com/data", {
  retry: {
    limit: 3,
    methods: ["get"],
    statusCodes: [408, 429, 500, 502, 503, 504],
    backoffLimit: 3000,
  },
  timeout: 10000,
}).json();
Enter fullscreen mode Exit fullscreen mode

Hooks: Intercept Requests

const api = ky.create({
  prefixUrl: "https://api.example.com",
  hooks: {
    beforeRequest: [
      (request) => {
        request.headers.set("Authorization", `Bearer ${getToken()}`);
      },
    ],
    afterResponse: [
      async (request, options, response) => {
        if (response.status === 401) {
          const newToken = await refreshToken();
          request.headers.set("Authorization", `Bearer ${newToken}`);
          return ky(request);
        }
      },
    ],
    beforeRetry: [
      ({ retryCount }) => {
        console.log(`Retry attempt ${retryCount}`);
      },
    ],
  },
});

const products = await api.get("products").json();
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,
    sort: "relevance",
  },
}).json();
Enter fullscreen mode Exit fullscreen mode

Form Data and Blobs

// Upload file
const formData = new FormData();
formData.append("file", blob, "data.csv");
formData.append("name", "export");

await ky.post("https://api.example.com/upload", { body: formData });

// Download as blob
const blob = await ky.get("https://api.example.com/export.csv").blob();
Enter fullscreen mode Exit fullscreen mode

vs fetch vs axios

Feature fetch Ky axios
Size 0KB 3KB 29KB
Retry No Yes Plugin
Timeout No Yes Yes
JSON shortcut No Yes Yes
Hooks No Yes Yes
Browser + Node Yes Yes Yes

Make HTTP requests for scraping? My Apify tools handle the heavy lifting.

Custom HTTP solution? Email spinov001@gmail.com

Top comments (0)