Install Ky, send a JSON request with a custom header, and read the JSON response body.
Ky is an HTTP client based on the Fetch API: pass a URL and options, then use a method shortcut and a body method to make a request and read its response.
Prerequisites
Ky targets modern browsers, Node.js, Bun, and Deno. The package requires Node.js 22 or newer.
Install
bashnpm install ky
Send a JSON request
-
Import the default
kyexport. Usejsonfor the request body andheadersfor the custom request header. Thepost()shortcut sends a POST request;json()reads and parses the response body.tsimport ky from 'ky'; const main = async (): Promise<void> => { const result = await ky.post('https://httpbin.org/anything', { json: {name: 'Ada'}, headers: { 'x-client': 'ky-quick-start', }, }).json(); console.log(result); }; void main();Inspect
resultin the console to see the parsed JSON response body. Its type isunknownby default; use a type argument when you know the response shape, or validate the response as described in Send and read JSON.
What you have
Your code sends a POST request with a JSON body and the x-client header, then logs the parsed response body. Ky sets the JSON content type for the json option unless you provide a Content-Type header yourself. A non-2xx response throws an HTTPError by default, and .json() also throws if the response body is empty.
Where to go next
- Send and read JSON for response typing and JSON handling.
- Add request headers for reusable headers.
- How Ky works for the core concepts.
Was this page helpful?