📅  最后修改于: 2023-12-03 15:35:31.718000             🧑  作者: Mango
Unsplash is a website that offers high-resolution photographs that are free to use for any purpose. You can access the Unsplash API through Javascript, which allows you to query Unsplash’s database and retrieve images for your web applications. In this article, we will explore how you can use Unsplash-Javascript to add beautiful images to your web applications with ease.
Unsplash-Javascript can be installed via NPM or by adding a script tag in your HTML.
npm install unsplash-js
Before you can use the Unsplash API, you will need to obtain an access key. You can easily generate an access key by creating an account on Unsplash's website. Once you have your access key, you can authenticate your requests by creating an instance of the Unsplash class with your access key.
const Unsplash = require('unsplash-js').default;
const unsplash = new Unsplash({ accessKey: "YOUR_ACCESS_KEY" });
You can search the vast Unsplash library for photos that match your criteria. To do this, you can use the searchPhotos
method. This method accepts an object with the query parameters.
unsplash.search.photos("dog", 1, 10)
.then(response => response.json())
.then(json => console.log(json));
This example searches for the term "dog", and retrieves the first 10 photos from the second page of the search results.
If you would like to retrieve a random photo, you can use the getRandomPhoto
method.
unsplash.photos.getRandomPhoto()
.then(response => response.json())
.then(json => console.log(json));
This example retrieves a random photo from the Unsplash library.
Unsplash-Javascript is a powerful tool that allows you to easily search and retrieve beautiful photos from Unsplash's vast library. By following this guide, you can start integrating stunning photos into your web applications today.