HTTP Just Got a Little Easier: A Beginner's Guide to Ky
HTTP Just Got a Little Easier: A Beginner's Guide to Ky was initially published on Saturday January 07 2023 on the Tech Dev Blog. For the latest up-to-date content, fresh out of the oven, visit https://techdevblog.io and subscribe to our newsletter!
Welcome to our tutorial on using Sindre Sorhus' ky
JavaScript library!
First off, what is ky
and why should you care? ky
is a small and simple library for making HTTP requests in JavaScript, with a straightforward API and support for both Node.js and the browser. It's lightweight, fast, and easy to use, making it a great choice for anyone looking to make HTTP requests in their JavaScript projects.
Now, let's dive into how to use ky
.
Installing ky
To use ky
, you'll first need to install it. You can do this with npm by running the following command:
npm install ky
Or, if you're using yarn:
yarn add ky
Making a Request
Making a request with ky
is simple. Just call the ky()
function with the URL you want to request, and you'll get back a Promise
that resolves with the response.
For example, to make a GET request to the GitHub API to fetch a list of repositories for a user, you could do the following:
const ky = require('ky');
(async () => {
const repositories = await ky('https://api.github.com/users/sindresorhus/repos');
console.log(repositories);
})();
That's it! You've just made your first request with ky
.
Customising the Request
Of course, you'll often want to customise your request beyond just the URL. ky
makes this easy by allowing you to pass an options object as the second argument.
For example, you can set the HTTP method, headers, and body of the request like this:
const ky = require('ky');
(async () => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'ky'
})
};
const response = await ky('https://httpbin.org/post', options);
console.log(response);
})();
You can also use the ky.get()
, ky.post()
, ky.put()
, and ky.delete()
functions to create requests with those specific HTTP methods, like this:
const ky = require('ky');
(async () => {
const options = {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'ky'
})
};
const response = await ky.post('https://httpbin.org/post', options);
console.log(response);
})();
Handling Responses
By default, ky
returns the raw response object from the server, which includes the status code, headers, and body of the response. You can access these properties directly from the response object:
const ky = require('ky');
(async () => {
const response = await ky('https://api.github.com/users/sindresorhus');
console.log(response.status); // prints the status code
console.log(response.headers); // prints the headers object
console.log(response.body); // prints the response body
})();
But what if you just want the response body as a JSON object, or a plain text string? ky
has you covered with the json()
and text()
methods.
const ky = require('ky');
(async () => {
const response = await ky('https://api.github.com/users/sindresorhus');
console.log(await response.json()); // prints the response body as a JSON object
console.log(await response.text()); // prints the response body as a string
})();
Handling Errors
As with any network request, things can go wrong. ky
will reject the returned promise if the request fails or the server returns a non-2xx status code. You can catch these errors using a try
/catch
block:
const ky = require('ky');
(async () => {
try {
const response = await ky('https://api.github.com/users/sindresorhus');
console.log(response);
} catch (error) {
console.error(error);
}
})();
Advanced Options
ky
has a number of advanced options that you can use to fine-tune your requests. Here are a few examples:
searchParams
: Allows you to set the query string parameters for the request.timeout
: Sets the timeout for the request in milliseconds.retry
: Allows you to retry the request if it fails. You can customise the number of retries and the delay between them.throwHttpErrors
: By default,ky
rejects the promise for non-2xx status codes. You can set this option tofalse
to disable this behaviour and instead resolve the promise with the response.
You can find a full list of options in the ky
documentation.
Wrapping Up
We hope this tutorial has given you a good understanding of how to use ky
to make HTTP requests in your JavaScript projects. ky
is a simple and powerful library that makes it easy to work with HTTP in Node.js and the browser, and we highly recommend giving it a try. Happy coding!
HTTP Just Got a Little Easier: A Beginner's Guide to Ky was initially published on Saturday January 07 2023 on the Tech Dev Blog. For the latest up-to-date content, fresh out of the oven, visit https://techdevblog.io and subscribe to our newsletter!