Giter VIP home page Giter VIP logo

unsplash-js's Introduction

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.


unsplash-js's People

Contributors

aaronklaassen avatar alextrastero avatar bado22 avatar beruic avatar cramhead avatar dcolonv avatar dechuck avatar dependabot[bot] avatar joshwcomeau avatar lukechesser avatar magellol avatar magicpoulp avatar mlegenhausen avatar naoufal avatar oliverjash avatar prewk avatar samhh avatar samijaber avatar spencerfdavis avatar tanishqkancharla avatar vincentdoerig avatar watadarkstar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unsplash-js's Issues

Terser v3.16.0 breaks react-scripts build

Steps to Reproduce

  • Create a new react project create-react-app something
  • Install unsplash-js
  • Attempt to build! npm run build

Observed Behaviour

> [email protected] build /Users/joe/unsplash-camera-stats
> react-scripts build

Creating an optimized production build...
Failed to compile.

Failed to minify the bundle. Error: static/js/main.2901663d.chunk.js from Terser
TypeError: Cannot read property 'minify' of undefined
    at compiler.run (/Users/joe/unsplash-camera-stats/node_modules/react-scripts/scripts/build.js:169:23)
    at finalCallback (/Users/joe/unsplash-camera-stats/node_modules/webpack/lib/Compiler.js:210:39)

Expected Behaviour

A successful build.

Technical Notes

PR incoming!

Response data

First of all, thanks for this awesome package๐Ÿ‘

This is rather a question.

Is there a situation when a response does not contain any of these raw, thumb, small, regular, full in url object as well as name and profile urls in user object when using unsplash.search.photos()?

I want to make sure if the data is always present or no.

`ReferenceError: fetch is not defined` - calling unsplash.photos.getPhoto

Hi,

I'm using unsplash in node.js and I'm coming up with following error message:

app[web.1]: ReferenceError: fetch is not defined
app[web.1]:     at Unsplash.request (/app/node_modules/unsplash-js/lib/unsplash.js:79:14)
app[web.1]:     at Object.getPhoto (/app/node_modules/unsplash-js/lib/methods/photos.js:77:20)

calling following code snippet:

unsplash.photos.getPhoto(imageId, 200, 1080, [0, 0, 1920, 1080])
    .then(toJson)
    .then(json => {
      console.log(json);
    });

Steps to Reproduce

In node.js imported and initialized unsplash-js

import Unsplash from 'unsplash-js';

const unsplash = new Unsplash({
  applicationId: "...",
  secret: "...",
  callbackUrl: "..."
});

determined a valid unsplash ID through my application logic and tried to call the API to retrieve additional info:

unsplash.photos.getPhoto(imageId, 200, 1080, [0, 0, 1920, 1080])
    .then(toJson)
    .then(json => {
      console.log(json);
    });

Observed Behaviour

Exception is thrown

Image or video please.
N/A

Technical Notes

Node.js hostend on heroku and started via

web: babel-node --presets es2015 main.js

API is never returning liked_by_user: true

Steps to Reproduce

Using unsplash-js package to fetch the photo

Observed Behaviour

It never returns the true value for liked_by_user even if I have liked it

Expected Behaviour

API should return liked_by_user: true if it is been liked by logged in user

import Unsplash

Steps to Reproduce

import Unsplash from 'unsplash-js';

const unsplash = new Unsplash({
applicationId: "{APP_ID}",
secret: "{APP_SECRET}",
callbackUrl: "{CALLBACK_URL}"
});

Observed Behaviour

When running file with above content in node, the error is
import Unsplash from 'unsplash-js';
SyntaxError: Unexpected token import

When running in Chrome browser, the error is
import Unsplash from 'unsplash-js';
"Uncaught syntax error: Unexpected Identifier"

Image or video please.

Expected Behaviour

The module imported successfuly as README example indicates it should

Technical Notes

Orientation parameter

Orientation parameter is added to the API but seems like we can't use it with this library, since there is no such parameter for the functions.

order_by "trending" possible?

How to get "Trending" photos as seen on unsplash.com? The order_by parameter only accepts latest, oldest and popular according to the docs.

Module name "unsplash-js" has not been loaded yet

Steps to Reproduce

  • HTML: <script async data-main="index.js" src="require.js"></script>
  • JavaScript:
// Require syntax
const Unsplash = require("unsplash-js").default;

const unsplash = new Unsplash({
  applicationId: "[removed]",
  secret: "[removed]"
});

Observed Behaviour

  • It errors.

Expected Behaviour

  • It to work as per the documentation.

Technical Notes

  • Error: Uncaught Error: Module name "unsplash-js" has not been loaded yet for context: _. Use require([])

UMD example fails

Steps to Reproduce

I've updated main.js file in UMD example folder with my app credentials and launched the server.

I changed main.js file like that:

var unsplash = new Unsplash.default({
    applicationId: "...Application ID...",
    secret: "...Secret key...",
    callbackUrl: "...Redirect URI..."
});

unsplash.users.profile("naoufal")
    .then(Unsplash.toJson)
    .then(function (json) {
        console.log(json);
    });

Observed Behaviour

I'm stuck with this error: OAuth error: The access token is invalid. I am not sure how to fix it.
Should I fill callback url field with redirect url from my app (unsplash.com/oauth/applications/...)?
Is this example up-to-date?

TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters

Steps to Reproduce

invoke "searchPhotos" with non-latin chars, for example Cyrillic "ะฐะฐะฐ"

Observed Behaviour

TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters
at new ClientRequest (_http_client.js:115:13)
at request (https.js:281:10)
.....

Image or video please.

Expected Behaviour

Query should be escaped when building the url within unsplashJS sdk

Technical Notes

No images in response data

Steps to Reproduce

unsplash.photos
.searchPhotos('bear', undefined, 1, 1)
.then(toJson)
.then(json => {
console.log(json);
});

Observed Behaviour

Response { size: 0, timeout: 0, [Symbol(Body internals)]: { body: PassThrough { _readableState: [Object], readable: true, domain: null, _events: [Object], _eventsCount: 7, _maxListeners: undefined, _writableState: [Object], writable: true, allowHalfOpen: true, _transformState: [Object] }, disturbed: false, error: null }, [Symbol(Response internals)]: { url: 'https://api.unsplash.com/photos/search?query=bear&category=&page=1&per_page=1', status: 200, statusText: 'OK', headers: Headers { [Symbol(map)]: [Object] } } }

Image or video please.

Expected Behaviour

get urls or ids of images?
Sorry but what am I doing wrong? I'm not getting the images... I thought they should be in the json data.

CORS Errors with HTML Canvas Elements

I'm using the IMG src value (a URL to any given image on Unsplash), and attempting to load that into an HTML canvas element. This is working splendidly in Chrome, but only in Chrome. In other browsers, I'm getting these errors:

[Error] Origin http://127.0.0.1:1337 is not allowed by Access-Control-Allow-Origin.
[Error] Failed to load resource: Origin http://127.0.0.1:1337 is not allowed by Access-Control-Allow-Origin. (photo-1533577871619-310ff191dd40, line 0)
[Error] Cross-origin image load denied by Cross-Origin Resource Sharing policy.

Obviously, this is running on localhost. I get the same when running a test deployment from Heroku.

Is there anything I can do on my side to fix this? Or is this something to do with the CORS configuration on the Unsplash side, that I cannot control?

require syntax for toJson function

I noticed that there is no require syntax for the toJson function from the unsplash-js module. Is there any other way to include its functionality other writing code in ES6 and transpiling with Babel?

Dependency on an insecure version of url-parse

Steps to Reproduce

Run npm audit

Observed Behaviour

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ High          โ”‚ Open Redirect                                                โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Package       โ”‚ url-parse                                                    โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Patched in    โ”‚ >=1.4.3                                                      โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Dependency of โ”‚ unsplash-js                                                  โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ Path          โ”‚ unsplash-js > url-parse                                      โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ More info     โ”‚ https://nodesecurity.io/advisories/678                       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Expected Behaviour

Don't depend on an old version of url-parse.

Technical Notes

Not sure whether it would be possible to actually exploit this in many cases.

Error: Couldn't find Photo

Steps to Reproduce

	unsplash.photos.getPhoto(req.params.id)
	.then(Unsplash.toJson)
	.then(json => {
		console.log(json);
		res.status(200).send(json);
	});

Observed Behaviour

Getting back the image's JSON object, and then an error object. The error object gets sent to page in the response.

Expected Behaviour

The image object should be sent to the page for use.

Technical Notes

Firing the request twice. The first time, I get just this logged to my console:

{ errors: [ 'Couldn\'t find Photo' ] }

The second request returns this. Note the repeat of the errors object at the end, as that's all that gets sent to the browser in the server response.

{ id: 'uIhcaulybPs',
  created_at: '2018-06-26T11:17:20-04:00',
  updated_at: '2018-07-07T11:51:23-04:00',
  width: 5725,
  height: 3000,
  color: '#F5E3D9',
  description: null,
  urls:
   { raw: 'https://images.unsplash.com/photo-1530026091265-6ab5b498c7f9?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjMwODgxfQ&s=0958aea945481aafca5e8e13525ec115',
     full: 'https://images.unsplash.com/photo-1530026091265-6ab5b498c7f9?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjMwODgxfQ&s=31d88cac43ec8c9dd674c8ec15768982',
     regular: 'https://images.unsplash.com/photo-1530026091265-6ab5b498c7f9?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjMwODgxfQ&s=688de0d57d0467c5e492589327c9e801',
     small: 'https://images.unsplash.com/photo-1530026091265-6ab5b498c7f9?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjMwODgxfQ&s=9215be05e55241b22098e03f10c66267',
     thumb: 'https://images.unsplash.com/photo-1530026091265-6ab5b498c7f9?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&ixid=eyJhcHBfaWQiOjMwODgxfQ&s=d4758204040b5f60d45f2b271700b180',
     custom: 'https://images.unsplash.com/photo-1530026091265-6ab5b498c7f9?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=&h=&rect=&fit=crop&ixid=eyJhcHBfaWQiOjMwODgxfQ&s=8ecf458a798379d2b73d258f9bec6d36' },
  links:
   { self: 'https://api.unsplash.com/photos/uIhcaulybPs',
     html: 'https://unsplash.com/photos/uIhcaulybPs',
     download: 'https://unsplash.com/photos/uIhcaulybPs/download',
     download_location: 'https://api.unsplash.com/photos/uIhcaulybPs/download' },
  categories: [],
  sponsored: false,
  likes: 37,
  liked_by_user: false,
  current_user_collections: [],
  slug: null,
  user:
   { id: 'LmREXrLdf2E',
     updated_at: '2018-07-07T19:10:51-04:00',
     username: 'hermez777',
     name: 'Hermes Rivera',
     first_name: 'Hermes',
     last_name: 'Rivera',
     twitter_username: 'hermez777',
     portfolio_url: null,
     bio: null,
     location: 'Windsor, ON, Canada',
     links:
      { self: 'https://api.unsplash.com/users/hermez777',
        html: 'https://unsplash.com/@hermez777',
        photos: 'https://api.unsplash.com/users/hermez777/photos',
        likes: 'https://api.unsplash.com/users/hermez777/likes',
        portfolio: 'https://api.unsplash.com/users/hermez777/portfolio',
        following: 'https://api.unsplash.com/users/hermez777/following',
        followers: 'https://api.unsplash.com/users/hermez777/followers' },
     profile_image:
      { small: 'https://images.unsplash.com/profile-1490219408060-29f9868b0c1b?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32&s=f87c1a5795a8b130a5b1faa9924826ab',
        medium: 'https://images.unsplash.com/profile-1490219408060-29f9868b0c1b?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64&s=e0211205e2939448081945361fd99933',
        large: 'https://images.unsplash.com/profile-1490219408060-29f9868b0c1b?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128&s=4ab78fd49337e3c41f46e65352c3e9db' },
     instagram_username: 'hermez777',
     total_collections: 2,
     total_likes: 20,
     total_photos: 212 },
  exif:
   { make: 'SONY',
     model: 'ILCE-6500',
     exposure_time: '1/160',
     aperture: '4.0',
     focal_length: '33.0',
     iso: 1600 },
  location:
   { title: 'Windsor, Canada',
     name: 'Windsor',
     city: 'Windsor',
     country: 'Canada',
     position: { latitude: 42.3149367, longitude: -83.0363633 } },
  views: 152316,
  downloads: 1309 }
{ errors: [ 'Couldn\'t find Photo' ] }

Random image call always returning the same image

Steps to Reproduce

I've run into an issue where my api call to photos/random always returns the same image. Previously this call had worked to return a different/random image on each call.

An example of the call I'm using is:
https://api.unsplash.com/photos/random/?query=books&client_id=myapikey

I've also experimented with adding a count parameter and in this case it seems to always return the same array of photos.

Observed Behaviour

I initially noticed this behavior in my app, but when testing the call in the browser I also see that it's returning the same image every time from this call.

Has this method changed or is this an issue on the Unsplash side?

getRandomPhoto() doesnt return image with specified width and height

I am trying to get random images with a specific width and height but it always outputs images with random dimensions.

Steps to Reproduce

unsplash.photos.getRandomPhoto({
  width: 1000,
  height: 1000,
  query: "nature",
  count: 1
})
  .then(Unsplash.toJson)
  .then(json => {
    var obj = JSON.stringify(json);

    fs.writeFile('image_urls.json', obj, 'utf8', function (err) {
      if (err) {
        return console.log(err);
      }
      console.log("The file was saved!")
    });
  });

Observed Behaviour

I get something like this back:

[{
    "id": "EafH-BTjj1Q",
    "created_at": "2016-09-13T10:46:28-04:00",
    "updated_at": "2018-05-18T13:09:07-04:00",
    "width": 5184,
    "height": 3456,
    "color": "#C4A274",
    "description": "View on a jagged side of a mountain with a forest at its base under a dark blue sky",
    ...

I am not sure why it's not working as count and query options work perfectly fine

Options headers for CORS

OPTIONS: Access-Control-Allow-Headers missing authorization and accept-version.

Are there any projects that actually use this? or is it only meant to be for node apps?

Cannot specify timeout for API requests

Steps to Reproduce

Issue an api request

Observed Behaviour

times out after default fetch timeout

Expected Behaviour

should be able to receive a timeout parameter via constructor

Technical Notes

Pull request #105

Adding orientation as a parameter for /search/photos endpoint

Request

Are there any plans to add orientation as a parameter to the search query?
I saw that this already exists and is available under /photos/random endpoint but unfortunately not
under the /search/photos endpoint.

It would be a great feature to implement to get more specific pictures, depending on what dimensions one needs.

Error trying to call public methods

Steps to Reproduce

  1. Initialize unsplash object.
  2. Call public method

Observed Behaviour

Server response with 401: "OAuth error: The access token is invalid":

image

image

Technical Notes

As I read in unslplash docs, if you want to access only to public methods, you don't need to use oauth. Instead, you have to use special headers providing your access key.

Authorization: Client-ID YOUR_ACCESS_KEY

But here we are using APPLICATION_ID instead ACCESS_KEY in the header: https://github.com/unsplash/unsplash-js/blob/master/src/utils/index.js#L32

I'm going to prepare a PR in order to fix this.

Secret Key not a secret?

Hello,

I have been trying to get my head around the terms and conditions, usage policy and the API docs but am finding some inconsistencies.

According to the requirements when you create an app. The Secret Key must remain confidential;
image

However, in the documentation for this library, you state that we must use the secret key to initialise the client. This makes the secret key redundant and exposed to anyone who wants to fumble around the source code of the application.

image

I'm unsure what the best practice is, but it is very concerning to include the secret key in the client side code, given that any user could take those credentials

Any advice would be great.

Relevance of pictures with many search terms

Steps to Reproduce

  • Search for "christmas"
  • Search for "christmas tree"

Observed Behaviour

  • The results are ordered exactly the same. "Tree" pictures are displayed after the pictures matching "christmas".

Expected Behaviour

  • Searching for "X Y" should sort first the image containing "X and Y".

I'm not sure if it's a feature or a bug. But I would be glad it could work.

The best would be to be able to write full-text queries like "christmas & tree" (see https://www.compose.com/articles/mastering-postgresql-tools-full-text-search-and-phrase-search).

Regards.

ๆƒณ้—ฎไธ€ไธ‹ๆˆ‘็š„่ฏทๆฑ‚ไธบไป€ไนˆๆฒกๆœ‰่ฟ”ๅ›žๅ›พ็‰‡็š„่ทฏๅพ„

Steps to Reproduce

`const Unsplash = require("unsplash-js").default;

const accessKey = "a37610fe0232b739c6cbabb7389a77ef10de6d31f5c07a4c99ffc0d8b3af31b4";
const secretKey = "b9d0e32cfb7b6d9b20def01b5edf320f008ffcb98a20c7240da780dfc5c6e82c";

const unsplash = new Unsplash({
applicationId: accessKey,
secret: secretKey,
callbackUrl:'http://unsplash-js.herokuapp.com'
});

unsplash.photos.getRandomPhoto()
.then(Unsplash.toJson)
.then(json => {
console.log(json);
});`

Observed Behaviour

body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://api.unsplash.com/photos/random?c=1561909448139"
proto: Response

Image or video please.

Expected Behaviour

Technical Notes

What is the value for callback_url?

What is the value for callback_url? I uses react-native and i cannot find what should be value for it. Is this optional?

Care to describe that on the documentation

Fetch is not defined with Unsplash package for Nodejs development environment

Environment: Nodejs

I think the README.md file should be updated base on comment: #35 (comment) for more detail for Nodejs user.

And I make another solution here:
Step 1: npm i --save unsplash-js node-fetch
Step 2: Create sample js file like this:

const Unsplash = require("unsplash-js").default;
const fetch = require('node-fetch');
global.fetch =fetch;

const unsplash = new Unsplash({
  applicationId: "yourId",
  secret: "yourSecret"
});
unsplash.photos
  .getRandomPhoto()
  .then(res => res.json())
  .then(json => {
    console.dir(json);
  });

Step 3: This should be worked.

Location information of images

Hi,

I just wanted to check if the API supports location where the image has taken (geotagging?). Right now I can only see the photographers location and not the location of the image.(It is available only for some images)

Also is it possible to sort images along with search keyword

Regards,
Smitha

Search photos and Sorting

Hi,

Can I search photos and sort them at the same time?
E.g. I want to search "phone" photos and can be sorted by 'popular' or 'latest'

I can find the order_by parameter in unsplash.listPhotos() but not in unsplash.searchPhotos()

Thanks,

Random images repeating after a while

Observed Behaviour

When is use count>1 and any search query in random photo api,the images tend to repeat after a while.
What i expect on each api call is fresh images.Is this expected behaviour?

Relevance of search results

Hi, I realize that this is not a bug and more of a feature request/question, so apologies for that.

I have a slight concern about the relevance of the search results returned from getRandomImage. For my specific use case, I need to get a picture of a city that I am querying by name. I.e. {query: denver}.

The problem obviously being that when anyone is tagging images with whatever they want, I don't really know what I'm going to get in my result. One particular example is Denver, a search here shows: https://unsplash.com/search/photos/denver
Picutres of lions, a cat, a car.

Unsplash does not seem to support searching by unions of keysโ€”for example, "denver city" will return images tagged denver and images tagged city.

In the perfect world, the return of that search result would be images that are tagged with a union of those search terms.

I've also noticed that the first image in the results is typically pretty relevant. On the Unsplash UI, if I search for any major US city, I'm typically going to be returned a city of the skyline as the first result.

So the question is twofold: 1) Is it possible to add some kind of keyword unioning so I can take a city name, append 'city' to the search, i.e. denver city and reliably be returned a picture of that city? 2) If not, is it possible to just be returned the most relevant image, or first result? It seems that Unsplash has some internal ranking going on, but I can not be sure.

If neither of these is supported, how would one suggest I go about this?

Thank you.

CORS issue on 500 responses

Hi, I'm using unsplash-js for a while and all was working fine, but now I have CORS issues. Here is the console log while running a simple unsplash.search.photos('food', 1, 30) :

GET https://api.unsplash.com/search/photos?query=food&page=1&per_page=30 503 ()

Failed to load https://api.unsplash.com/search/photos?query=food&page=1&per_page=30: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 503. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.-

Is it a problem on Unsplash side ?

Thanks

Option for specifying image file size window

Steps to Reproduce

Is there any option available to specify a max file size while getting the images.

Observed Behaviour

Image or video please.

Expected Behaviour

Technical Notes

unsplash.search.photos returns same photo every time

It is more of a question, does unsplash.search.photos should return a random photo, or not?

Steps to Reproduce

unsplash.search
    .photos(uniqueQuery, 1, 1)
    .then(toJson)

Where uniqueQuery is the value from an input + Number(new Date());

Observed Behaviour

  • For the same input value, I am receiving the same photo every time. It doesn't say in the documentation if the returned photo should be random or not, but maybe it is related to: #56

Expected Behaviour

  • receive a random photo for the same query on different calls

Technical Notes

  • experiencing the same behavior with:
https://api.unsplash.com/search/photos?client_id=my_client_id&query=coffee&page=1&per_page=1&unique=12334k

I cannot use in React Native

Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.
TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.

photos.getPhoto() - a question on rectangle

Been trying to use the photos.getPhoto(id, width, heigth, rectangle) function but I still struggle understanding what the function will actually return when I specify rectangle.

Steps to Reproduce

I have used the following to retrieve an image from the api:

unsplash.photos.getPhoto("KXWXvR8mSi4", 1920, 1080, [100, 100, 200, 200])
  .then(toJson)
  .then((json) => {
    console.log(json);
  });

Observed Behaviour

I get the following url pointing to the image (1920*1080).

Expected Behaviour

I thought that the array rectangle was actually going to define the frame that would be used to crop the image using coordinates as follow: [x1, y1, x2, y2]. In other words, I was expecting to retrieve an image of 100*100 in that example, as illustrated on the image below.

photo-1501570569038-b5460067c722

Question

Is it possible to get some clarifications on how is rectangle going to impact what is returned?

Thanks!

How to save photo to local disk for use

Steps to Reproduce

  • Is there any way that I can save a photo to my local directories, at the moment the downloadPhoto() function returns a response, which does contain a url, however the url gives the following error:
    {"errors":["OAuth error: The access token is invalid"]}
    How do I get the donwload link to save the photo locally?

(The app won't be published publicly, it's for a University project).
unsplash.search.photos("Blessed", 1).then(toJson).then(json => {

unsplash.photos.downloadPhoto(json.results[0]).then(photo => {
    console.log(photo);
}).catch(error => {
    console.log(error);
});

}).catch(error => {
console.log('Could not find photo on Unpslash.');
});

Observed Behaviour

  • Response {
    size: 0,
    timeout: 0,
    [Symbol(Body internals)]:
    { body:
    PassThrough {
    _readableState: [ReadableState],
    readable: true,
    _events: [Object],
    _eventsCount: 2,
    _maxListeners: undefined,
    _writableState: [WritableState],
    writable: false,
    allowHalfOpen: true,
    _transformState: [Object] },
    disturbed: false,
    error: null },
    [Symbol(Response internals)]:
    { url: 'https://api.unsplash.com/photos/-S-OKXUfFjA/download?',
    status: 200,
    statusText: 'OK',
    headers: Headers { [Symbol(map)]: [Object] },
    counter: 0 } }

Image or video please.

Expected Behaviour

Technical Notes

Get multiple photos by ID

Hey there,

Is it at all possible to query for multiple photos if I have an array of photo IDs? The only way I can think of currently is to loop through the desired photo IDs and do a photos.getPhoto() for each, which may be costly if the list of IDs gets long...

Could search.photos() perhaps also accept an array for the keyword parameter and also query by photo ID?

Thanks!

dist version?

It would be nice if you guys had a dist version that I could just import into my app with a script tag. unsplash.min.js. Thanks for considering it... not everyone is using react and webpack. I can do this myself of course but it would be nice if I didn't have to and it would make your api accessible to more developers. Even better if you had it on a CDN. Check out auth0 for a good example of a lot of installation options in their api. Anyway thanks for considering it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.