• Stars
    star
    2,027
  • Rank 22,840 (Top 0.5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿค– Official JavaScript wrapper for the Unsplash API

Unsplash

npm

Official Javascript wrapper for the Unsplash API.

Key Links:

Documentation

Installation

$ npm i --save unsplash-js

# OR

$ yarn add unsplash-js

Dependencies

Fetch

This library depends on fetch to make requests to the Unsplash API. For environments that don't support fetch, you'll need to provide polyfills of your choosing. Here are the ones we recommend:

Adding polyfills

createApi receives an optional fetch parameter. When it is not provided, we rely on the globally scoped fetch.

This means that you can set the polyfills in the global scope:

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

// browser
import 'whatwg-fetch';

or explicitly provide them as an argument:

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

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

Note: we recommend using a version of node-fetch higher than 2.4.0 to benefit from Brotli compression.

node-fetch and global types

This library presumes that the following types exist in the global namespace:

  • fetch
  • RequestInit
  • Response

By default TypeScript defines these via the "dom" type definitions.

However, if you're targeting Node and you're using node-fetch you should omit the "dom" type definitions using the lib compiler option and then define the required global types manually like so:

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

declare global {
  var fetch: typeof nodeFetch.default;
  type RequestInit = nodeFetch.RequestInit;
  type Response = nodeFetch.Response;
}
global.fetch = nodeFetch.default;

const unsplash = createApi({
  accessKey: 'MY_ACCESS_KEY',
  fetch: nodeFetch.default,
});

Unfortunately this won't work with node-fetch v3 due to an issue in node-fetch, whereby the global namespace is polluted with the "dom" type definitions: node-fetch/node-fetch#1285.

As a workaround you use a type assertion:

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

const unsplash = createApi({
  accessKey: 'MY_ACCESS_KEY',
  fetch: nodeFetch.default as unknown as typeof fetch,
});

URL

This library also depends on the WHATWG URL interface:

Note: Make sure to polyfill this interface if targetting older environments that do not implement it (i.e. Internet Explorer or Node < v8).

Note 2: For Node, the URL interface exists under require('url').URL since v8 but was only added to the global scope as of v10.0.0. If you are using a version between v8.0.0 and v10.0.0, you need to add the class to the global scope before using unsplash-js:

URL = require('url').URL;

Usage

Creating an instance

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

NOTE: If you're using unsplash-js publicly in the browser, you'll need to proxy your requests through your server to sign the requests with the Access Key to abide by the API Guideline to keep keys confidential. We provide an apiUrl property that lets you do so. You should only need to provide one of those two values in any given scenario.

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({
  apiUrl: 'https://mywebsite.com/unsplash-proxy',
  //...other fetch options
});

Making a request

Arguments

All methods have 2 arguments: the first one includes all of the specific parameters for that particular endpoint, while the second allows you to pass down any additional options that you want to provide to fetch. On top of that, the createApi constructor can receive fetch options to be added to every request:

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

unsplash.photos.get(
  { photoId: '123' },
  // `fetch` options to be sent only with _this_ request
  { headers: { 'X-Custom-Header-2': 'bar' } },
);

Example: if you would like to implement request abortion, you can do so like this:

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

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

unsplash.photos.get({ photoId: '123' }, { signal }).catch(err => {
  if (err.name === 'AbortError') {
    console.log('Fetch aborted');
  }
});

controller.abort();

Response

When making a request using this SDK, there are 2 possible outcomes to a request.

  • Error: we return a result.errors object containing an array of strings (each one representing one error) and result.source describing the origin of the error (e.g. api, decoding). Typically, you will only have on item in this array.
  • Success: we return a result.response object containing the data.
    • If the request is for a page from a feed, then result.response.results will contain the JSON received from API, and result.response.total will contain the X-total header value indicating the total number of items in the feed (not just the page you asked for).
    • If the request is something other than a feed, then result.response will contain the JSON received from API

You can inspect which one you have by reading the result.type value or checking the contents of result.errors/result.success

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

// non-feed example
unsplash.photos.get({ photoId: 'foo' }).then(result => {
  if (result.errors) {
    // handle error here
    console.log('error occurred: ', result.errors[0]);
  } else {
    // handle success here
    const photo = result.response;
    console.log(photo);
  }
});

// feed example
unsplash.users.getPhotos({ username: 'foo' }).then(result => {
  if (result.errors) {
    // handle error here
    console.log('error occurred: ', result.errors[0]);
  } else {
    const feed = result.response;

    // extract total and results array from response
    const { total, results } = feed;

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

NOTE: you can also pattern-match on result.type whose value will be error or success:

unsplash.photos.get({ photoId: 'foo' }).then(result => {
  switch (result.type) {
    case 'error':
      console.log('error occurred: ', result.errors[0]);
    case 'success':
      const photo = result.response;
      console.log(photo);
  }
});

Types

The types for this library target TypeScript v3.7 and above.

This library is written in TypeScript. This 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 IDE such as VSCode) to fully benefit from this information:

Function arguments

Response Types

Instance Methods

NOTE: All of the method arguments described here are in the first parameter. See the arguments section for more information.


More Repositories

1

react-trend

๐Ÿ“ˆ Simple, elegant spark lines
JavaScript
2,480
star
2

datasets

๐ŸŽ 4,800,000+ Unsplash images made available for research and machine learning
Jupyter Notebook
2,224
star
3

unsplash-php

๐Ÿ‘ป Official PHP wrapper for the Unsplash API
PHP
408
star
4

unsplash-photopicker-ios

๐Ÿ“ฑAn iOS photo picker to search and download photos from Unsplash.
Swift
390
star
5

unsplash-photopicker-android

๐Ÿ“ฑAn Android photo picker to search and download photos from Unsplash.
Kotlin
327
star
6

unsplash_rb

๐Ÿ’Ž Ruby wrapper for the Unsplash API.
Ruby
224
star
7

unsplash-source-js

๐Ÿฎ A javascript wrapper for the Unsplash Source API
JavaScript
176
star
8

comment-on-pr

A GitHub Action to comment on the relevant open PR when a commit is pushed.
Ruby
146
star
9

swiftui-lazycollectionview

A modest attempt to port UICollectionView to SwiftUI.
Swift
136
star
10

react-progressive-enhancement

A handy collection of HOCs for universally renderedย apps
TypeScript
63
star
11

intlc

Compile ICU messages into code. Supports TypeScript and JSX. No runtime.
Haskell
51
star
12

uploader-prototype

An open-source prototype of the Unsplash uploader.
TypeScript
45
star
13

sum-types

Safe, ergonomic, non-generic sum types in TypeScript.
TypeScript
41
star
14

url-transformers

Small helper library for manipulating URL strings in Node and in the browser.
TypeScript
35
star
15

ts-imgix

Strongly-typed imgix URL builder function, `buildImgixUrl`.
TypeScript
32
star
16

ts-namespace-import-plugin

Auto import common namespaces in your modules
TypeScript
30
star
17

pipe-ts

TypeScript
30
star
18

request-frp

`request-frp` is a package that provides pure wrappers around `fetch` and `XMLHttpRequest`.
TypeScript
14
star
19

ts-redux-finite-state-machine-example

TypeScript
13
star
20

tinplate

โญ๏ธ TinEye API wrapper
Ruby
13
star
21

responsive-image-test

TypeScript
12
star
22

unsplash-imageview-ios

A UIImageView subclass that displays a random photo from Unsplash.
Swift
9
star
23

imagga-auto-tag

๐ŸŽฉ Ruby client for fetching tags from the Imagga Auto Tagging API
Ruby
8
star
24

sum-types-fast-check

fast-check bindings for @unsplash/sum-types.
TypeScript
3
star
25

swift-storyboard-identifiers

A script that generates identifiers strings from .storyboard files.
Ruby
2
star
26

service-dash

๐Ÿ”ฅ Is anything on fire?
Ruby
2
star
27

mercury

The guide of souls to the underworld.
Rust
2
star
28

imgix-trackable

๐Ÿ›ฐ Tracklable Imgix URLs via the ixid param
TypeScript
2
star
29

sum-types-io-ts

io-ts bindings for @unsplash/sum-types.
TypeScript
2
star
30

ts-type-tests-example

TypeScript
2
star
31

import-sort-style-unsplash

TypeScript
2
star
32

sum-types-fp-ts

fp-ts bindings for @unsplash/sum-types.
TypeScript
2
star
33

translations-connector-test

1
star