Go Client for the Unsplash API

Overview

Unsplash API client

GoDoc Build Status Coverage Status codecov Go Report Card Codacy Badge

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(
  &oauth2.Token{AccessToken: "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.

Comments
  • use 2-legged client auth

    use 2-legged client auth

    As per the documentation, 2-legged OAuth2 is preferred if you're not running as a third party. As this is a provided feature, it's simpler to set up and requires one less parameter.

    opened by klauern 5
  • Return Rate limiting error

    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.

    needs-investigation 
    opened by hbagdi 5
  • Add license scan report and status

    Add license scan report and status

    Your FOSSA integration was successful! Attached in this PR is a badge and license report to track scan status in your README.

    Below are docs for integrating FOSSA license checks into your CI:

    opened by fossabot 2
  • User.PortfolioURL is not always a valid URL

    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.

    opened by mjquigley 2
  • Errors with ListOpt{} when not specifying all values

    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

    opened by klauern 2
  • Process errors JSON when an error occurs and put in struct response

    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.

    enhancement 
    opened by hbagdi 2
  • Add Alt Text, Tags and other fields

    Add Alt Text, Tags and other fields

    Thank you for this convenient library.

    I needed a few more fields unmarshalled from the API responses, so this PR adds them.

    Note that the tag object in the API response can have an extensive source property which I did not include. Nor did I attempt to exhaustively include all fields in all response types.

    opened by martinroberts 1
  • Accept-Version: v1 headers should be added to each request

    Accept-Version: v1 headers should be added to each request

    Source : https://unsplash.com/documentation#version

    It seems like the API might move to a v2 at some point. Need to make a breaking change to the New() method to pass a config struct.

    A solution for now would be setting the header in do() before every request.

    opened by hbagdi 1
  • Utilize a dependency manager ('dep', 'glide', etc.)

    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.

    opened by klauern 1
  • Get a photo’s statistics

    Get a photo’s statistics

    Retrieve total number of downloads, views and likes of a single photo, as well as the historical breakdown of these stats in a specific timeframe (default is 30 days). https://unsplash.com/documentation#get-a-photos-statistics

    GET /photos/:id/statistics

    Similar to #9

    needs-investigation feature 
    opened by hbagdi 1
  • Fetch random photos filtering by topics

    Fetch random photos filtering by topics

    Hi! This PR adds the possibility to fetch random photos specifying the topic IDs. Since in the API documentation it's said that:

    Note: You can’t use the collections or topics filtering with query parameters in the same request

    I also added this check at the already existing CollectionIDs.

    opened by MDeLuise 0
  • Feature: introduce un.Users.Statistics method as well

    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.

    needs-investigation feature design-issue 
    opened by hbagdi 0
  • user.Photos(); user.Portfolio();user.Followers() - links in user

    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.

    help wanted feature 
    opened by hbagdi 1
Releases(1.0.1)
Client-go - Clusterpedia-client supports the use of native client-go mode to call the clusterpedia API

clusterpedia-client supports the use of native client-go mode to call the cluste

clusterpedia.io 9 Sep 2, 2022
A Go client implementing a client-side distributed consumer group client for Amazon Kinesis.

Kinesumer is a Go client implementing a client-side distributed consumer group client for Amazon Kinesis.

당근마켓 66 Aug 21, 2022
Nutanix-client-go - Go client for the Nutanix Prism V3 API

nutanix-client-go This repository contains portions of the Nutanix API client code in nutanix/terraform-provider-nutanix. It has been extracted to red

Marvin Beckers 0 Jan 6, 2022
Go client for the YNAB API. Unofficial. It covers 100% of the resources made available by the YNAB API.

YNAB API Go Library This is an UNOFFICIAL Go client for the YNAB API. It covers 100% of the resources made available by the YNAB API. Installation go

Bruno Souza 52 Sep 12, 2022
An API client for the Notion API implemented in Golang

An API client for the Notion API implemented in Golang

Anatoly Nosov 333 Sep 24, 2022
A Wrapper Client for Google Spreadsheet API (Sheets API)

Senmai A Wrapper Client for Google Spreadsheet API (Sheets API) PREPARATION Service Account and Key File Create a service account on Google Cloud Plat

ytnobody / satoshi azuma 0 Nov 5, 2021
Simple-Weather-API - Simple weather api app created using golang and Open Weather API key

Simple Weather API Simple weather api app created using golang and Open Weather

Siva Prakash 3 Feb 6, 2022
Client for the cloud-iso-client

cloud-iso-client Client for the cloud-iso-client. Register an API token Before using this client library, you need to register an API token under your

Virtomize 0 Dec 6, 2021
Go-http-client: An enhanced http client for Golang

go-http-client An enhanced http client for Golang Documentation on go.dev ?? This package provides you a http client package for your http requests. Y

Furkan Bozdag 41 Sep 12, 2022
Aoe4-client - Client library for aoe4 leaderboards etc

AOE4 Client Overview This is a go client used to query AOE4 data from either the

Mark Smith 0 Jan 18, 2022
Balabola-go-client - GO client for Yandex balabola service

Balabola GO Client GO client for Yandex balabola service Yandex warning The neur

Konovalov Maxim 0 Jan 29, 2022
Client-server-golang-sqs - Client Server with SQS and golang

Client Server with SQS and golang Multi-threaded client-server demo with Go What

null 0 Feb 14, 2022
Go Client Library for Amazon Product Advertising API

go-amazon-product-advertising-api Go Client Library for Amazon Product Advertising API How to Use go get -u github.com/ngs/go-amazon-product-advertisi

Atsushi NAGASE 54 Sep 27, 2022
A Go client library for the Twitter 1.1 API

Anaconda Anaconda is a simple, transparent Go package for accessing version 1.1 of the Twitter API. Successful API queries return native Go structs th

Aditya Mukerjee 1.1k Sep 27, 2022
Go client library for interacting with Coinpaprika's API

Coinpaprika API Go Client Usage This library provides convenient way to use coinpaprika.com API in Go. Coinpaprika delivers full market data to the wo

Coinpaprika 15 Aug 8, 2022
Golang client for ethereum json rpc api

Ethrpc Golang client for ethereum JSON RPC API. web3_clientVersion web3_sha3 net_version net_peerCount net_listening eth_protocolVersion eth_syncing e

Andrey 245 Sep 27, 2022
Package githubv4 is a client library for accessing GitHub GraphQL API v4 (https://developer.github.com/v4/).

githubv4 Package githubv4 is a client library for accessing GitHub GraphQL API v4 (https://docs.github.com/en/graphql). If you're looking for a client

null 918 Sep 20, 2022
📟 Tiny utility Go client for HackerNews API.

go-hacknews Tiny utility Go client for HackerNews API. Official Hackernews API Install go get github.com/PaulRosset/go-hacknews Usage Few examples a

Paul Rosset 15 Sep 1, 2022
A golang client for the Twitch v3 API - public APIs only (for now)

go-twitch Test CLIENT_ID="<my client ID>" go test -v -cover Usage Example File: package main import ( "log" "os" "github.com/knspriggs/go-twi

Kristian Spriggs 21 May 10, 2021