Unsplash
PhotographyAccessing the Unsplash API with JavaScript
Unsplash is a popular website that offers free high-quality photos from photographers around the world. They also provide a public API that you can use to access their database of images and metadata. In this article, we'll explore how to access the Unsplash API with JavaScript, using examples of different endpoints.
Getting started
Before we can start using the Unsplash API, we need to get an API key. To get your API key, sign up for an account on https://unsplash.com/join and then create a new application on https://unsplash.com/developers.
Authentication
Once you have your API key, you'll need to include it as an Authorization header in your API requests. Here's an example of how to do this in JavaScript:
const headers = {
Authorization: 'Client-ID YOUR_ACCESS_KEY',
};
Endpoints
Now that we have our API key and headers set up, let's look at some example code for accessing different endpoints on the Unsplash API.
Search photos
const query = 'dogs';
const url = `https://api.unsplash.com/search/photos?query=${query}`;
fetch(url, { headers })
.then((response) => response.json())
.then((data) => console.log(data.results))
.catch((error) => console.log(error));
This code searches for photos related to "dogs" and logs the results to the console.
Random photo
const url = 'https://api.unsplash.com/photos/random';
fetch(url, { headers })
.then((response) => response.json())
.then((data) => console.log(data.urls.regular))
.catch((error) => console.log(error));
This code gets a random photo from Unsplash and logs the URL of its regular-sized image to the console.
Get collections
const url = 'https://api.unsplash.com/collections';
fetch(url, { headers })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
This code gets a list of collections on Unsplash and logs them to the console.
Get collection photos
const collectionId = '12345';
const url = `https://api.unsplash.com/collections/${collectionId}/photos`;
fetch(url, { headers })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
This code gets all the photos in a collection with the ID of 12345 and logs them to the console.
Conclusion
That's it! With these examples, you should now be able to access the Unsplash API with JavaScript and fetch photos and data to use in your applications. Remember to always include your API key in your requests to avoid any errors. If you want to learn more about the Unsplash API and its features, visit https://unsplash.com/developers.