Skip to content

unsplash/unsplash-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

549 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Unsplash

npm

Official JavaScript wrapper for the Unsplash API.

Key Links:

Documentation

Installation

$ npm i --save unsplash-js

# OR

$ yarn add unsplash-js

Usage

Creating an instance

To create an instance, simply provide an Object with your accessKey.

import { createApi } from "unsplash-js";

// on your node server
const serverApi = createApi({
  accessKey: "MY_ACCESS_KEY",
  //...other fetch options
});

// in the browser
const browserApi = createApi({
  baseUrl: "https://mywebsite.com/unsplash-proxy",
  //...other fetch options
});

NOTE: If you're using unsplash-js in the browser, you must proxy your requests through your server by setting baseUrl. This is to authenticate requests with your Access Key to abide by the API Guideline, and keeps your keys confidential. If baseUrl is set, accessKey is unnecessary and vice-versa.

Making a request

createApi returns an instance whose methods each accept a params object and standard fetch options.

Each method is named after an HTTP verb (GET, POST, DELETE, PUT, PATCH).

const unsplash = createApi({
  accessKey: "MY_ACCESS_KEY",
});

unsplash.GET("/photos/{assetSlug}", {
  params: { path: { assetSlug: "123" } },
});

Global fetch options can be set on the constructor; per-request fetch options override them:

const unsplash = createApi({
  accessKey: "MY_ACCESS_KEY",
  // `fetch` options to be sent with every request
  headers: { "X-Custom-Header": "foo" },
});

unsplash.GET("/photos/{assetSlug}", {
  params: { path: { assetSlug: "123" } },
  // `fetch` options to be sent with only this request
  headers: { "X-Custom-Header-2": "bar" },
});

Example: Using an AbortController on a specific request:

const unsplash = createApi({
  accessKey: "MY_ACCESS_KEY",
});

const controller = new AbortController();
const signal = controller.signal;

unsplash
  .GET("/photos/{assetSlug}", {
    params: { path: { assetSlug: "123" } },
    signal,
  })
  .catch((err) => {
    if (err.name === "AbortError") {
      console.log("Fetch aborted");
    }
  });

controller.abort();

Response

There are two possible outcomes to a request:

  1. You received data: result.data is present and populated.
  2. The server returned an error: result.error is present and contains error details.

If you'd like to inspect the full response, result.response contains the raw Response object. You can use this to get the X-Total header value on feed responses, for example.

const unsplash = createApi({ accessKey: "MY_ACCESS_KEY" });

// non-feed example
const result = await unsplash.GET("/photos/{assetSlug}", {
  params: { path: { assetSlug: "foo" } },
});

if (result.error) {
  // handle error here
  console.log("error occurred: ", result.error.errors[0]);
} else {
  // handle success here
  const photo = result.data;
  console.log(photo);
}

// feed example
const result = await unsplash.GET("/users/{username}/photos", {
  params: { path: { username: "foo" } },
});

if (result.error) {
  // handle error here
  console.log("error occurred: ", result.error.errors[0]);
} else {
  // extract total and results array from response
  const feed = result.data;
  const total = parseInt(result.response.headers.get("x-total"));

  // handle success here
  console.log(`received ${feed.length} photos out of ${total}`);
  console.log("first photo: ", feed[0]);
}

NOTE: All usual fetch exceptions can get thrown when making requests using this library.

Authentication

When using the accessKey parameter on the createApi constructor, the Authorization header will be automatically set to use public authentication.

If you need to use either the user authentication or dynamic client registration scheme, set the Authorization header on each request according to the requirements of the authentication method you've chosen.

Replacing fetch

This is useful when mocking fetch in tests, targeting an older runtime, or providing a custom fetch implementation.

Fetch can be replaced globally or as an argument to createApi.

// Globally

// server
import fetch from "node-fetch";
global.fetch = fetch;

// browser
import "whatwg-fetch";
// As an argument to `createApi`

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

const unsplash = createApi({
  accessKey: "MY_ACCESS_KEY",
  fetch: nodeFetch,
});

See the openapi-fetch documentation for more information.

Types

The types for this library target TypeScript v4.5 and above.

This library is written in TypeScript, which means that even if you are writing plain JavaScript, you can still get useful and accurate type information. We highly recommend that you setup your environment (using an editor such as VSCode) to fully benefit from type hinting:

Request completion

Response completion

Endpoint examples

createApi returns a preconfigured openapi-fetch instance whose methods correspond to the usual HTTP verbs (.GET, .POST, .PUT, .DELETE, .PATCH).

For a full list of Unsplash's public endpoints, see the API documentation.

The endpoints covered here are grouped by category:

For a full list of all available endpoints and their parameters, see the OpenAPI spec.


About

🤖 Official JavaScript wrapper for the Unsplash API

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors