A server-side Javascript wrapper for working with the Unsplash API.
Before using the Unsplash API, you need to register as a developer and read the API Guidelines.
Quick links to methods you're likely to care about:
- Get a list of new photos 🎉
- Get a random photo 🎑
- Trigger a photo download 📡
- Search for a photo by keyword 🕵️♂️
Note: Every application must abide by the API Guidelines. Specifically, remember to hotlink images, attribute photographers, and trigger a download when appropriate.
$ npm i --save unsplash-js
This library depends on fetch to make requests to the Unsplash API. For environments that don't support fetch, you'll need to provide a polyfill.
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 and/or Secret Key to abide by the API Guideline to keep keys confidential.
To create an instance, simply provide an Object with your access key
and secret
.
// ES Modules syntax
import Unsplash from 'unsplash-js';
// require syntax
const Unsplash = require('unsplash-js').default;
const unsplash = new Unsplash({
applicationId: "{APP_ACCESS_KEY}",
secret: "{APP_SECRET}"
});
If you already have a bearer token, you can also provide it to the constructor.
const unsplash = new Unsplash({
applicationId: "{APP_ACCESS_KEY}",
secret: "{APP_SECRET}",
callbackUrl: "{CALLBACK_URL}",
bearerToken: "{USER_BEARER_TOKEN}"
});
You can also provide headers that will be set on every request by providing them to the constructor.
const unsplash = new Unsplash({
applicationId: "{APP_ACCESS_KEY}",
secret: "{APP_SECRET}",
headers: {
"X-Custom-Header": "foo"
}
});
Credentials can be obtained from Unsplash Developers.
For use with React Native, import from unsplash-js/native
instead.
import Unsplash from 'unsplash-js/native';
Generate an authentication url with the scopes your app requires.
const authenticationUrl = unsplash.auth.getAuthenticationUrl([
"public",
"read_user",
"write_user",
"read_photos",
"write_photos"
]);
Now that you have an authentication url, you'll want to redirect the user to it.
location.assign(authenticationUrl);
After the user authorizes your app she'll be redirected to your callback url with a code
querystring present. Request an access token using that code.
// The OAuth code will be passed to your callback url as a querystring
unsplash.auth.userAuthentication(query.code)
.then(toJson)
.then(json => {
unsplash.auth.setBearerToken(json.access_token);
});
For more information on the authroization workflow, consult the Unsplash Documentation.
unsplash.users.profile("naoufal")
.catch(err => {
// Your flawless error handling code
});
All the instance methods below make use of the toJson
helper method described below