Overview
In this tutorial, we will dive into how to search for and download images by keyword from the Unsplash API using Node.js. Unsplash is a platform powered by a community of photographers that offers free high-resolution photos. By leveraging their API, you can access these resources directly from your application.
Pre-requisites
- Node.js installed on your machine
- An understanding of JavaScript and async/await
- An Unsplash Developer Account and API Access Key
Step-by-Step Instructions
Step 1: Setting Up Your Project
Firstly, create a new Node.js project by initiating it with npm init
in your terminal in a new directory. Install the necessary packages using npm:
npm install axios fs-extra
axios
will be used for making HTTP requests to the Unsplash API, and fs-extra
aids in handling file downloads and operations.
Step 2: Configure Your API Access
Head over to the Unsplash Developer page, sign up for an account, and create a new application to obtain your Access Key. Keep this key secure as it allows you to query the Unsplash API.
Step 3: Searching for Images by Keyword
Create a new file called searchUnsplash.js
and start by importing the axios module:
const axios = require('axios');
Define your API Access Key:
const accessKey = 'YOUR_UNSPLASH_ACCESS_KEY';
Now let’s create a function to search for images on Unsplash based on a keyword:
async function searchImages(keyword) {
try {
const response = await axios.get(`https://api.unsplash.com/search/photos`, {
params: {
query: keyword,
client_id: accessKey
}
});
console.log(response.data.results);
return response.data.results;
} catch (error) {
console.error(error);
}
}
This function makes a GET request to the search/photos endpoint of the Unsplash API, passing in the search keyword and our access key as parameters. The results are then logged to the console.
Step 4: Downloading Images
Having obtained the search results, the next step is to download these images. Create another function in the searchUnsplash.js
file:
const fs = require('fs-extra');
const path = require('path');
async function downloadImage(imageUrl, filename) {
const response = await axios({
url: imageUrl,
method: 'GET',
responseType: 'stream',
});
const writer = fs.createWriteStream(path.resolve(__dirname, 'downloads', filename));
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}
This function downloads an image from a given URL and saves it under a specified filename within a ‘downloads’ directory.
Step 5: Tying It All Together
Now that we have our search and download functions, let’s use them to find and then download images by a keyword:
async function findAndDownload(keyword) {
const images = await searchImages(keyword);
images.forEach(async (image, index) => {
const { urls, alt_description } = image;
await downloadImage(urls.regular, `${keyword}-${index}.jpg`);
console.log(`Downloaded: ${alt_description || 'Image'}`);
});
}
Remember to replace ‘YOUR_UNSPLASH_ACCESS_KEY’ with your actual Unsplash API access key.
Conclusion
By following this tutorial, you should now have a basic understanding of how to interact with the Unsplash API using Node.js to search for and download images based on keywords. This can be incredibly useful for projects that require dynamic image content without the overhead of manually sourcing and saving these resources.
While we’ve covered the basics, remember that the Unsplash API offers much more functionality, including but not limited to fetching random photos, photo statistics, and user information. Explore the Unsplash documentation to fully leverage its capabilities in your applications.
This tutorial also touches on important programming concepts such as asynchronous JavaScript, API interaction, and file handling in Node.js, providing a solid foundation for further learning and development.