Git Product home page Git Product logo

unsplash_rb's Introduction

unsplash_rb

Build Status Coverage Status

A ruby client for the Unsplash API.

Installation

Add this line to your application's Gemfile:

gem 'unsplash'

And then execute:

$ bundle

Or install it yourself as:

$ gem install unsplash

Usage

Configuration

Before making requests, you must configure the gem with your application ID and secret. If you are using Rails, you can do this in an initializer.

Unsplash.configure do |config|
  config.application_access_key = "YOUR ACCESS KEY"
  config.application_secret = "YOUR APPLICATION SECRET"
  config.application_redirect_uri = "https://your-application.com/oauth/callback"
  config.utm_source = "alices_terrific_client_app"

  # optional:
  config.logger = MyCustomLogger.new
end

API Guidelines

All API applications must abide by the API Guidelines.

As part of the API guidelines, all API uses are required to use utm links when providing credit to photographers and Unsplash. Set the config.utm_source to your app's name to automatically append the utm source.

Public-scope actions

If you are only making public requests (i.e. nothing requiring a specific logged-in user, for example liking photos or accessing private user details), then you're ready to go!

Looking for details of a specific photo? Find it by ID:

photo = Unsplash::Photo.find("tAKXap853rY")

Want a bunch of pictures of cats? You're on the internet; of course you do.

search_results = Unsplash::Photo.search("cats")

For a complete list of available actions, see our documentation details.

User Authorization

For non-public actions, you'll have to get the user's permission to access their data. Direct them to the Unsplash authorization URL:

requested_scopes = ["public", "read_user", "something_else_you_are_asking_for"]
auth_url = Unsplash::Client.connection.authorization_url(requested_scopes)

Upon authorization, Unsplash will return to you an authentication code via your OAuth callback handler. With that you can generate an access token:

Unsplash::Client.connection.authorize!("the authentication code")

And that's it. The API actions will be available to you according to whichever permission scopes you requested and the user authorized.

Hotlinking

Hotlinking the Unsplash image files is required

Unlike most APIs, Unsplash requires for the image URLs returned by the API to be directly used or embedded in your applications (generally referred to as hotlinking). By using the CDN and embedding the photo URLs in your application, Unsplash can better track photo views and pass those stats on to the photographer, providing them with context for how popular their photo is and how it's being used.

Track Download

Do you want to trigger track download attribution on a photo ?

photo = Unsplash::Photo.find("tAKXap853rY")
photo.track_download

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake rspec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/unsplash/unsplash_rb. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

unsplash_rb's People

Contributors

aaronklaassen avatar adimasuhid avatar arbourd avatar arg avatar equivalent avatar gmaliar avatar gustavosobral avatar hakubjozak avatar jigar786 avatar lukechesser avatar mateomurphy avatar matthiaswinkelmann avatar mth4saurabh avatar scarroll32 avatar snsavage avatar stanhuan avatar twe4ked 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

unsplash_rb's Issues

Timeout

It would be great to be able to set a http timeout on some of the requests done by the Unsplash SDK, or to have a reasonable default built into the library itself.

Any chance you can add this?

OAuth gem dependency is EOL

Steps to Reproduce

Install the Unsplash gem

Observed Behaviour

Install will succeed, but with a warning:

You have installed oauth2 version 1.4.10, which is EOL.
No further support is anticipated for the 1.4.x series.

OAuth2 version 2 is released.
There are BREAKING changes, but most will not encounter them, and upgrading should be easy!

Please see:
β€’ https://github.com/oauth-xx/oauth2#what-is-new-for-v20
β€’ https://github.com/oauth-xx/oauth2/blob/master/CHANGELOG.md

Please upgrade, report issues, and support the project! Thanks, |7eter l-|. l3oling

Technical Notes

I can see in the Gemspec that Unsplash is locking the oauth2 gem to v1.x (

spec.add_dependency "oauth2", "~> 1"
). If possible, this condition should be relaxed to allow support for newer versions of oauth2 to be installed.

category.rb deprecated

Steps to Reproduce

Just use category.rb function. And say
'WARN -- : Category endpoints are deprecated. Use Collections instead.'

Observed Behaviour

Use ruby to network.

Expected Behaviour

Remove this code about category, just remain collection.

Add a note about hotlinking

Add a note about hotlinking/embedding images returned from the Unsplash API directly in applications.

Link to the official API documentation at https://unsplash.com/documentation#hotlinking

In the official documentation I said:

Unlike most APIs, we prefer for the image URLs returned by the API to be directly used or embedded in your applications (generally referred to as hotlinking). By using our CDN and embedding the photo URLs in your application, we can better track photo views and pass those stats on to the photographer, providing them with context for how popular their photo is and how it's being used.

Change to the third person and it should be good.

Retrieving response headers

Is there any easy way to get at the response headers like X-Ratelimit-Remaining? This would be very useful for tracking our rate limiting. Unless I'm missing something (I could be), the only way would be to use the Connection class directly to get the full response rather than just the body.

Documentation is out-of-date (curated API)

Steps to Reproduce

Observed Behaviour

Unsplash::Photo.curated
=> NoMethodError: undefined method `curated' for Unsplash::Photo:Class

Expected Behaviour

  • Documentation is updated to reflect that the method has been removed

Technical Notes

Ruby version is old

The Ruby version for this gem is 2.4.0. I will submit a PR to update it to 2.4.5.

Do the maintainers think it should perhaps be updated to the latest version, ie: 2.6.1 ?

Number total of elements and pages

Hello guys!

When using classes search method, the gem only retrieves the array of searched entity. As, if you call the Unsplash::Photo.search method, it will retrieve an array of Unsplash::Photo objects. This way, it misses some API response [1] information. As the total number of elements on that query (total), and the total of pages by that query with that number of elements per page (total_pages). Are any plans in mind to solve this behavior or something that I can do? I believe that kind of change will probably release a new major gem version?

Thanks

[1] https://unsplash.com/documentation#search-photos

Deprecate Photo#create

The API's photo-upload endpoint has been deprecated and removed. Change Photo#create to raise an Unsplash::Error rather than try (and fail) to upload something.

Add code coverage badge

Overview

Should help build trust that the library is well maintained and covered since users of the gem know how complete our test coverage is.

Issues with the orientation parameter: returning invalid value

Steps to Reproduce

  1. Tried: Unsplash::Photo.search("cat", 1, 5, orientation: :landscape)
    Unsplash::Error: orientation is invalid, orientation does not have a valid value
    from /Users/joshledgard/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/unsplash-3.1.1/lib/unsplash/connection.rb:152:in `request'

  2. Tried Unsplash::Photo.search("cat", 1, 5, 'landscape')

WARN -- : The tags property in this endpoint is deprecated. https://changelog.unsplash.com/deprecations/2021/07/12/tags-search-deprecation.html

Observed Behaviour

See the error message and the warning above for the two calls.

Expected Behaviour

A way to set an orientation.

Technical Notes

using latest 3.1.1.

undefined method `application_access_key='

Steps to Reproduce

Follow Readme to setup
start rails server

Observed Behaviour

This error occurs undefined method application_access_key=' for #Unsplash::Configuration:0x00007fb668f1aec0 (NoMethodError)`

Apparently looking into the code, gem installed not the latest version. defaulting back to previous code of config.application_id from the suggested config.application_access_key
will make it work again if your unsplash version is not 2.0(unsure which version but def <= 1.4.1)

suggest changing readme gem 'unsplash' to gem 'unsplash', '~> 2.0.0'

Dead link in `utm_source` warning

Steps to Reproduce

  • Attempt to make an API call without configuring the utm_source parameter:
Unsplash.configure do |config|
  config.application_access_key = KEY
  config.application_secret = SECRET
end
Unsplash::Photo.search("cats")

Observed Behaviour

  • Warning appears in console. The provided link is dead.
W, [2019-05-14T11:35:01.126289]  WARN -- : utm_source is required as part of API Terms: https://community.unsplash.com/developersblog/unsplash-api-guidelines
=> [#<Unsplash::Photo:0x00007faabac32690 ...>]

Expected Behaviour

  • The link should go to a real page

Technical Notes

This presumably just needs to be updated with a new value.

url = "https://community.unsplash.com/developersblog/unsplash-api-guidelines"

Missing utm params for links

Steps to Reproduce

  • Search for any image with ruby library. ie: Unsplash::Photo.search("cats")

Observed Behaviour

  • For every result, we have the links either to the images or the the photographer, but those links does not contain the utm params

Image or video please.

Expected Behaviour

  • If understood correctly, Unsplash guidelines states that when hotlinking an image or linking to the User public profile, utm params should appear un the url.

Technical Notes

  • As the gem already handles utm configuration, it would be really helpful if the links returned by the gem would contain the utm params so we don't need to add them afterwards. I can work on a PR if everyone agree on that change

Unsplash::Photo.search raise error when per_page provided

running:

Unsplash::Photo.search('dog', per_page: 12, page: 1)

anywhere, rails c, controller, test

will raise exception

Unsplash::Error (page is invalid)
  • unsplash (2.1.0)
  • ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
  • rails 6.0.2

Combining `collections` and `query` parameters

Steps to Reproduce

  • Request a random photo using both the collections and query parameters, e.g.
    response = Unsplash::Photo.random(
      collections: [my_collection_id],
      query:       "cats"
    )

Observed Behaviour

  • A random photo from the my_collection_id collection is returned, ignoring the query parameter.
  • This seemed to be by design as per the API documentation (quote below), but there's no warning for using both parameters; I wonder if it just uses whichever is passed first.

Note: You can’t use the collections and query parameters in the same request

Expected Behaviour

  • In an ideal situation, it'd be nice to be able to use both parameters: specifying a list of collections and also searching by keyword within those collections.
  • In a more realistic situation, I suppose some kind of "You can't use both of these keys together" warning would help tinkering coders figure out why one parameter or the other is being ignored.

Technical Notes

  • I'm just getting into the Unsplash API and figuring out how I can help spread the awesome images you all have to more creatives, and would love to know if there is some alternative suggestion for combining collections with query or if it's just entirely not possible.

  • For reference, my use-case is generating personalized writing prompts for authors within the context of pre-built worlds within a worldbuilding app. I'm still exploring the options, but my first prototype was to have a collection for sci-fi images, a collection for modern images, fantasy images, historical images, etc (which works all and well), but I'd also like to give authors a bit more control over what's in the prompts they see, both explicitly (e.g. the author says "I want green landscapes" within a sci-fi world) or implicitly (e.g. the author has a redheaded man they haven't fleshed out, so I might want to append "redhead", "male", etc to some search results to better massage the images returned toward their world).

  • I could also make do with just collections or just queries (by having a ton of very specific collections, or by accepting that some queried results across all of Unsplash might not be "writing prompt" material, even if they are great images), but ideally I'm looking for something in the middle.

Thanks for any advice or guidance you can provide!

Failed to open TCP connection to images.unsplash.com:443 (execution expired) (Net::OpenTimeout)

Steps to Reproduce

require 'unsplash'
require 'open-uri'
require 'net/http'

Configure the Unsplash gem

Unsplash.configure do |config|
config.application_access_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
config.application_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
config.utm_source = "Recommendation_Travels"
end

Search for photos with the keyword "Dubai"

search_results = Unsplash::Photo.search("Dubai")

Initialize a counter for file naming

counter = 1

Download the photos and trigger the download tracking

search_results.each do |photo|

Format the counter to have leading zeros, creating a filename like dubai_001.jpg

filename = "dubai_#{format('%03d', counter)}.jpg"

Download the photo with an extended timeout (e.g., 30 seconds)

download_url = photo.urls.full
uri = URI(download_url)
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = 30 # Set the timeout to 30 seconds

response = http.request_get(uri)
if response.code.to_i == 200
File.open(filename, 'wb') do |file|
file.write response.body
end
else
puts "Failed to download photo: HTTP response code #{response.code}"
end

Trigger the download tracking for attribution

Unsplash::Photo.find(photo.id).track_download

Increment the counter for the next filename

counter += 1
end

puts "Downloaded and tracked #{search_results.size} photos of Dubai."

Observed Behaviour

Image or video please.

Expected Behaviour

ruby download_photo.rb
W, [2023-11-01T21:32:13.826060 #162007] WARN -- : The tags property in this endpoint is deprecated. https://changelog.unsplash.com/deprecations/2021/07/12/tags-search-deprecation.html
Traceback (most recent call last):
16: from download_photo.rb:56:in <main>' 15: from /home/adesoji/gems/gems/delegate-0.3.0/lib/delegate.rb:87:in method_missing'
14: from /home/adesoji/gems/gems/delegate-0.3.0/lib/delegate.rb:87:in each' 13: from download_photo.rb:66:in block in

'
12: from /usr/lib/ruby/2.7.0/net/http.rb:1393:in request_get' 11: from /usr/lib/ruby/2.7.0/net/http.rb:1483:in request'
10: from /usr/lib/ruby/2.7.0/net/http.rb:933:in start' 9: from /usr/lib/ruby/2.7.0/net/http.rb:1485:in block in request'
8: from /usr/lib/ruby/2.7.0/net/http.rb:1492:in request' 7: from /usr/lib/ruby/2.7.0/net/http.rb:1518:in transport_request'
6: from /usr/lib/ruby/2.7.0/net/http.rb:1567:in begin_transport' 5: from /usr/lib/ruby/2.7.0/net/http.rb:958:in connect'
4: from /home/adesoji/gems/gems/timeout-0.4.0/lib/timeout.rb:193:in timeout' 3: from /home/adesoji/gems/gems/timeout-0.4.0/lib/timeout.rb:186:in block in timeout'
2: from /usr/lib/ruby/2.7.0/net/http.rb:960:in block in connect' 1: from /usr/lib/ruby/2.7.0/net/http.rb:960:in open'
/usr/lib/ruby/2.7.0/net/http.rb:960:in `initialize': Failed to open TCP connection to images.unsplash.com:443 (execution expired) (Net::OpenTimeout)

Technical Notes

  • Rubv version 2.7

Can anyone help me out? i want to download the pictures of Dubai

Search return Unsplash::Error - orientation does not have a valid value

Steps to Reproduce

Unsplash::Photo.search('test', 1, 100)

Observed Behaviour

API returns error Unsplash::Error - orientation does not have a valid value

Notes

I am a bit confused since the documentation doesn't seem to allow you to pass an orientation option in the search method, I tried it anyway passing Unsplash::Photo.search('test',1, 100, orientation: 'landscape') but it returned the same error.

Update specs to allow non-local cassette recordings

Currently spec_helper has configuration that points at an instance of Unsplash running on localhost. Obviously that doesn't work for most people. πŸ˜… Update that config and the cassettes so they record from api.unsplash.com. That way contributors can record their own cassettes.

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.