Unsplash JavaScript API Wrapper

7.0.20 · abandoned · verified Sun Apr 19

unsplash-js is the official JavaScript wrapper for the Unsplash API, providing a convenient way to interact with Unsplash's photo services. The library abstracts away direct HTTP requests, offering methods for accessing photos, users, collections, and search functionalities. The current stable version is 7.0.20. Historically, it saw frequent minor updates for new API features and bug fixes, as evidenced by the recent v7.0.x releases. However, as of the latest README, the project has been officially archived and no longer receives support or updates, meaning new API features from Unsplash will not be integrated into this library, and critical bug fixes are unlikely. Developers are now directed to use the Unsplash developer documentation to make requests directly to the API, rather than relying on this wrapper.

Common errors

Warnings

Install

Imports

Quickstart

Initializes the Unsplash API client with an access key and fetches a random landscape photo, demonstrating basic API interaction and best practices for Node.js with `node-fetch` and TypeScript.

import { createApi } from 'unsplash-js';
import nodeFetch from 'node-fetch';

// Ensure global fetch types are available for TypeScript in Node.js
declare global {
  var fetch: typeof nodeFetch.default;
  type RequestInit = nodeFetch.RequestInit;
  type Response = nodeFetch.Response;
}

// Set global fetch for Node.js if not already present
if (typeof global !== 'undefined' && !global.fetch) {
  global.fetch = nodeFetch.default;
}

const MY_ACCESS_KEY = process.env.UNSPLASH_ACCESS_KEY ?? '';

if (!MY_ACCESS_KEY) {
  console.error('UNSPLASH_ACCESS_KEY environment variable is not set.');
  process.exit(1);
}

const unsplash = createApi({
  accessKey: MY_ACCESS_KEY,
  // Optional: Provide node-fetch explicitly if not setting globally, or for type compatibility
  fetch: nodeFetch.default as unknown as typeof fetch,
});

async function getRandomPhoto() {
  try {
    const result = await unsplash.photos.getRandom({
      count: 1,
      orientation: 'landscape',
    });

    if (result.type === 'success' && result.response.length > 0) {
      const photo = result.response[0];
      console.log('Random Photo:', photo.urls.regular);
      console.log('Photographer:', photo.user.name);
      console.log('Download URL (trigger download):', photo.links.download_location);
    } else if (result.type === 'error') {
      console.error('Failed to fetch random photo:', result.errors);
    }
  } catch (error) {
    console.error('An unexpected error occurred:', error);
  }
}

getRandomPhoto();

view raw JSON →