Examples of Using Ky
1. Basic GET Request
Ky makes fetching data from an API as simple as it gets. Here’s how you can retrieve data from a JSON API:import ky from 'ky';
(async () => {
try {
const data = await ky.get('https://jsonplaceholder.typicode.com/todos/1').json();
console.log('Fetched data:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
})();
2. POST Request with JSON Data
Sending data to a server is just as easy. Here’s an example of a POST request with JSON payload:import ky from 'ky';
(async () => {
try {
const response = await ky.post('https://jsonplaceholder.typicode.com/posts', {
json: {
title: 'My New Post',
body: 'This is the content of my post.',
userId: 1,
},
}).json();
console.log('Server response:', response);
} catch (error) {
console.error('Error submitting data:', error);
}
})();
Why it’s great: Ky automatically sets the Content-Type header to application/json when you pass a json object.
3. Handling Errors Gracefully
Ky throws errors for non-2xx status codes, making error handling a breeze:import ky from 'ky';
(async () => {
try {
const response = await ky.get('https://jsonplaceholder.typicode.com/invalid-endpoint').json();
console.log('Response:', response);
} catch (error) {
console.error('Error:', error.message); // Logs: "HTTP error 404"
}
})();
Why it’s great: Ky provides detailed error messages, including the HTTP status code, making debugging easier.
4. Adding Custom Headers
Need to add authentication or custom headers? Ky has you covered:import ky from 'ky';
(async () => {
try {
const response = await ky.get('https://api.example.com/protected', {
headers: {
Authorization: 'Bearer YOUR_ACCESS_TOKEN',
},
}).json();
console.log('Protected data:', response);
} catch (error) {
console.error('Error fetching protected data:', error);
}
})();
5. Timeouts and Retries
Ky allows you to set timeouts and automatically retry failed requests:import ky from 'ky';
(async () => {
try {
const response = await ky.get('https://api.example.com/slow-endpoint', {
timeout: 5000, // 5-second timeout
retry: 3, // Retry up to 3 times on failure
}).json();
console.log('Response:', response);
} catch (error) {
console.error('Request failed:', error);
}
})();
Why Ky is the Future of HTTP Requests
- Lightweight: Ky is tiny in size, making it perfect for performance-focused projects.
- Intuitive API: Its simple and consistent API reduces boilerplate code.
- Modern Features: Automatic JSON parsing, error handling, and timeout/retry support make it a joy to use.
- Cross-Platform: Works seamlessly in both Node.js and browsers.