Code Monkey home page Code Monkey logo

go-unsplash's Introduction

Unsplash API client

GoDoc CI Test Go Report Card

A wrapper for the Unsplash API.

Unsplash provides freely licensed high-resolution photos that can be used for anything.

Documentation

Installation

go get github.com/hbagdi/go-unsplash/unsplash

Dependencies

This library has a single dependency on Google's go-querystring.

API Guidelines

When using the Unsplash API, you need to make sure to abide by their API guidelines and API Terms.

Registration

Sign up on Unsplash.com and register as a developer.
You can then create a new application and use the AppID and Secret for authentication.

Help

Please open an issue in this repository if you need help or want to report a bug.
Mail at the e-mail address in the license if needed.

Usage

Importing

Once you've installed the library using go get, import it to your go project:

import "github.com/hbagdi/go-unsplash/unsplash"

Authentication

Authentication is not handled by directly by go-unsplash.
Instead, pass an http.Client that can handle authentication for you.
You can use libraries such as oauth2.
Please note that all calls will include the OAuth token and hence, http.Client should not be shared between users.

Note that if you're just using actions that require the public permission scope, only the AppID is required.

Creating an instance

An instance of unsplash can be created using New().
The http.Client supplied will be used to make requests to the API.

ts := oauth2.StaticTokenSource(
  // note Client-ID in front of the access token
  &oauth2.Token{AccessToken: "Client-ID Your-access-token"},
)
client := oauth2.NewClient(oauth2.NoContext, ts)
//use the http.Client to instantiate unsplash
unsplash := unsplash.New(client)  
// requests can be now made to the API
randomPhoto, _ , err := unsplash.RandomPhoto(nil)

Error handling

All API calls return an error as second or third return object. All successful calls will return nil in place of this return. Further, go-unsplash has errors defined as types for better error handling.

randomPhoto, _ , err := unsplash.RandomPhoto(nil)
if err != nil {
  //handle error
}

Response struct

Most API methods return a *Response along-with the result of the call.
This struct contains paging and rate-limit information.

Pagination

Pagination is currently supported by supplying a page number in the ListOpt. The NextPage field in Response can be used to get the next page number.

searchOpt := &SearchOpt{Query : "Batman"}
photos, resp, err := unsplash.Search.Photos(searchOpt)

if err != nil {
  return
}
// process photos
for _,photo := range *photos {
  fmt.Println(*photo.ID)
}
// get next
if !resp.HasNextPage {
  return
}
searchOpt.Page = resp.NextPage
photos, resp ,err = unsplash.Search.Photos(searchOpt)
//photos now has next page of the search result

Photos

Unsplash.Photos is of type PhotosService.
It provides various methods for querying the /photos endpoint of the API.

Random

You can get a single random photo or multiple depending upon opt. If opt is nil, then a single random photo is returned. Random photos satisfy all the parameters specified in *RandomPhotoOpt.

photos, resp, err := unsplash.Photos.Random(nil)
assert.Nil(err)
assert.NotNil(photos)
assert.NotNil(resp)
assert.Equal(1, len(*photos))
var opt RandomPhotoOpt
opt.Count = 3
photos, resp, err = unsplash.Photos.Random(&opt)
assert.Nil(err)
assert.NotNil(photos)
assert.NotNil(resp)
assert.Equal(3, len(*photos))

All photos

Get all photos on unsplash.com.
Obviously, this is a huge list and hence can be paginated through.

opt := new(unsplash.ListOpt)
opt.Page = 1
opt.PerPage = 10

if !opt.Valid() {
    fmt.Println("error with opt")
    return
}
count := 0
for {
    photos, resp, err := un.Photos.All(opt)

    if err != nil {
        fmt.Println("error")
        return
    }
    //process photos
    for _, c := range *photos {
        fmt.Printf("%d : %d\n", count, *c.ID)
        count += 1
    }
    //go for next page
    if !resp.HasNextPage {
        return
    }
    opt.Page = resp.NextPage
}

Curated Photos

Get all curated photos on unsplash.com.
Obviously, this is a huge list and hence can be paginated through.

opt := new(unsplash.ListOpt)
opt.Page = 1
opt.PerPage = 10

if !opt.Valid() {
    fmt.Println("error with opt")
    return
}
count := 0
for {
    photos, resp, err := un.Photos.Curated(opt)

    if err != nil {
        fmt.Println("error")
        return
    }
    //process photos
    for _, c := range *photos {
        fmt.Printf("%d : %d\n", count, *c.ID)
        count += 1
    }
    //go for next page
    if !resp.HasNextPage {
        return
    }
    opt.Page = resp.NextPage
}

Photo

Get details of a specific photo.

photo, resp, err := unsplash.Photos.Photo("9BoqXzEeQqM", nil)
assert.NotNil(photo)
assert.NotNil(resp)
assert.Nil(err)
fmt.Println(photo)
//photo is of type *Unsplash.Photo

// you can also specify a PhotoOpt to get a custom size or cropped photo
var opt PhotoOpt
opt.Height = 400
opt.Width = 600
photo, resp, err = unsplash.Photos.Photo("9BoqXzEeQqM", &opt)
assert.NotNil(photo)
assert.NotNil(resp)
assert.Nil(err)
log.Println(photo)
//photo.Urls.Custom will have the cropped photo
// See PhotoOpt for more details

Like

//Like a random photo
photos, resp, err := unsplash.Photos.Random(nil)
assert.Nil(err)
assert.NotNil(photos)
assert.NotNil(resp)
assert.Equal(1, len(*photos))
photoid := (*photos)[0].ID
photo, resp, err := unsplash.Photos.Like(*photoid)
assert.Nil(err)
assert.NotNil(photo)
assert.NotNil(resp)

Unlike

Same way as Like except call Unlike().

Download Link

Get download URL for a photo.

url, resp, err := unsplash.Photos.DownloadLink("-HPhkZcJQNk")
assert.Nil(err)
assert.NotNil(url)
assert.NotNil(resp)
log.Println(url)

Stats

Statistics for a specific photo

stats, resp, err := unsplash.Photos.Stats("-HPhkZcJQNk")
assert.Nil(err)
assert.NotNil(stats)
assert.NotNil(resp)
log.Println(stats)

Collections

Various details about collection(s).

All collections

collections, resp, err = unsplash.Collections.All(nil)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collections)
opt := new(ListOpt)
opt.Page = 2
opt.PerPage = 10
//get the second page
collections, resp, err = unsplash.Collections.All(opt)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collections)

Curated collections

collections, resp, err := unsplash.Collections.Curated(nil)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collections)

Featured collections

Same as Curated, but use Featured() instead.

Related collections

Get collections related to a collection.

collections, resp, err := unsplash.Collections.Related("296", nil)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collections)
//page through if necessary

Collection

Details about a specific collection

collection, resp, err := unsplash.Collections.Collection("910")
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collection)

Create collection

Create a collection on behalf of the authenticated user.

var opt CollectionOpt
title := "Test42"
opt.Title = &title
collection, resp, err := unsplash.Collections.Create(&opt)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collection)

Delete collection

Let's delete the collection just created above.

//get list of collections of a user
collections, resp, err := unsplash.Users.Collections("gopher", nil)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collections)
//take the first one
collection := (*collections)[0]
assert.NotNil(collection)
//delete it
resp, err = unsplash.Collections.Delete(*collection.ID)
assert.NotNil(resp)
assert.Nil(err)

Update collection

//get a user's collection
collections, resp, err := unsplash.Users.Collections("gopher", nil)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collections)
// take the first one
collection := (*collections)[0]
assert.NotNil(collection)
log.Println(*collection.ID)
//random title
var opt CollectionOpt
title := "Test43" + strconv.Itoa(rand.Int())
opt.Title = &title
//update the title
col, resp, err := unsplash.Collections.Update(*collection.ID, &opt)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(col)

Add photo

photos, resp, err := unsplash.Photos.Random(nil)
photo := (*photos)[0]
//get a user's collection
collections, resp, err := unsplash.Users.Collections("gopher", nil)
assert.Nil(err)
collection := (*collections)[0]
//add the photo
resp, err = unsplash.Collections.AddPhoto(*collection.ID, *photo.ID)
assert.Nil(err)

Remove photo

//remove a photo
_, _ = unsplash.Collections.RemovePhoto(*collection.ID, *photo.ID)

Users

Details about an unsplash.com users.

User

Details about unsplash.com users.

profileImageOpt := &ProfileImageOpt{Height: 120, Width: 400}
//or pass a nil as second arg
user, err := unsplash.Users.User("lukechesser", profileImageOpt)
assert.Nil(err)
assert.NotNil(user)

//OR, get the currently authenticated user
user, resp, err := unsplash.CurrentUser()
assert.Nil(user)
assert.Nil(resp)
assert.NotNil(err)

Portfolio

url, err = unsplash.Users.Portfolio("gopher")
assert.Nil(err)
assert.NotNil(url)
assert.Equal(url.String(), "https://wikipedia.org/wiki/Gopher")

Liked Photos

photos, resp, err := unsplash.Users.LikedPhotos("lukechesser", nil)
assert.Nil(err)
assert.NotNil(photos)
assert.NotNil(resp)

User photos

Get photos a users has uploaded on unsplash.com

photos, resp, err := unsplash.Users.Photos("lukechesser", nil)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(photos)

User collections

Get a list of collections created by the user.

collections, resp, err := unsplash.Users.Collections("gopher", nil)
assert.Nil(err)
assert.NotNil(resp)
assert.NotNil(collections)

Search

Search for photos, collections or users.

Search photos

var opt SearchOpt
//an empty search will be erroneous
photos, resp, err := unsplash.Search.Photos(&opt)
assert.NotNil(err)
assert.Nil(resp)
assert.Nil(photos)
opt.Query = "Nature"
//Search for photos tageed "Nature"
photos, _, err = unsplash.Search.Photos(&opt)
log.Println(len(*photos.Results))
assert.NotNil(photos)
assert.Nil(err)

Search collections

var opt SearchOpt
opt.Query = "Nature"
collections, _, err = unsplash.Search.Collections(&opt)
assert.NotNil(collections)
assert.Nil(err)
log.Println(len(*collections.Results))

Search users

var opt SearchOpt
opt.Query = "Nature"
users, _, err = unsplash.Search.Users(&opt)
log.Println(len(*users.Results))
assert.NotNil(users)
assert.Nil(err)

License

Copyright (c) 2017 Hardik Bagdi [email protected]

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

go-unsplash's People

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

Watchers

 avatar  avatar  avatar

go-unsplash's Issues

Feature: introduce un.Users.Statistics method as well

This is related to #9
There will two ways of doing the same thing.
Once via as a method on user struct and another directly on the UserService via a username.

Both will need a new opt struct to specify resolution and quantity.

Parameters
param Description
username The user’s username. Required.
resolution The frequency of the stats. (Optional; default: “days”)
quantity The amount of for each stat. (Optional; default: 30)

Currently, the only resolution param supported is “days”. The quantity param can be any number between 1 and 30.

Errors with ListOpt{} when not specifying all values

When using ListOpt to populate List Options, you need to specify all values for the options rather than each as you need them. For instance, I have to specify Page, PerPage and OrderBy if I want it to work, otherwise it fails with opt provided is not valid:

	photos, resp, err := u.Photos.Curated(&unsplash.ListOpt{
		OrderBy: unsplash.Popular,
	})

Will create an error

Search results missing Link headers

Unsplash /search endpoints don't return a Link header for pagination support.
Their dev has acknowledged the bug and they are going to fix it soon.
There's nothing much to be done here except wait and test the code again.

User.PortfolioURL is not always a valid URL

Issue

The Unsplash API can return invalid URLs for the User.PortfolioURL in the case I ran into the url contained a whitespace character at the end of the url. This causes parsing the entire response to fail.

Potential Fix

Changing User.PortfolioURL to *string instead of *Url should work and handle any invalid URLs there since it's not clear if Unsplash will verify that the url the user enters is valid. Otherwise updating Url.UnmarshalJSON to trim whitespace before parsing should at least eliminate some of these errors. It could also be a good idea to more gracefully handle errors here so parsing the entire response doesn't fail due to a single malformed URL.

Return Rate limiting error

The current code is returning AuthError even for a rate limiting case.
unsplash's API doesn't give a resume time header but since they do it per hour, upon hitting the rate limit, just don't send the request till the next hour begins. Needs much more though.

Process errors JSON when an error occurs and put in struct response

Current implementation drops the errors fields returned by the API whenever an API error occurs.
Explore the possibility of including this errors fields.
The current implementation has custom errors and signals those errors based on HTTP response codes.
This would require exploring what kind of errors the API returns.

Reture a Response in all calls

Currently a few of the API methods don't have a return Response object which has rate limiting and pagination info.
This needs to be uniform across every API call.

RandomPhotoOpt needs to be updated

More filters are introduced in the API
https://unsplash.com/documentation#get-a-random-photo
Get a random photo
Retrieve a single random photo, given optional filters.

GET /photos/random
Note: See the note on hotlinking.

Parameters
All parameters are optional, and can be combined to narrow the pool of photos from which a random one will be chosen.

param Description
collections Public collection ID(‘s) to filter selection. If multiple, comma-separated
featured Limit selection to featured photos.
username Limit selection to a single user.
query Limit selection to photos matching a search term.
w Image width in pixels.
h Image height in pixels.
orientation Filter search results by photo orientation. Valid values are landscape, portrait, and squarish.
count The number of photos to return. (Default: 1; max: 30)
Note: You can’t use the collections and query parameters in the same request

Note: When supplying a count parameter - and only then - the response will be an array of photos, even if the value of count is 1.

Update /stats/total endpoint

seems like the endpoint previously used to return int values but now one of them returns a string.
Probably because of overflow??

The change is to write a custom UnmarshalJSON for the GlobalStats struct.

Utilize a dependency manager ('dep', 'glide', etc.)

I think it would make sense to adopt a dependency management tool to allow reproducable builds and such. I have been bitten by this with another web service API, so at least trialling out 'dep' or something similar would be a good start.

user.Photos(); user.Portfolio();user.Followers() - links in user

Users have the following link relations:

photos API location of this user’s photos.
portfolio API location of this user’s external portfolio.
followers API location of this user’s followers.
following API location of users this user is following.

Need to expose methods for each of these.

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.