A Python Library to interface with Flickr REST API, OAuth & JSON Responses

Overview

Python-Flickr

Python-Flickr is A Python library to interface with Flickr REST API & OAuth

Features

  • Photo Uploading
  • Retrieve user information
  • Common Flickr methods
    • Add/edit/delete comments
    • Add/edit/delete notes
    • And many more (very dynamic library)!!
  • All responses return as nice dicts

Installation

Installing Python-Flickr is simple:

$ pip install python-flickr

Usage

Authorization URL

f = FlickrAPI(api_key='*your app key*',
          api_secret='*your app secret*',
          callback_url='http://www.example.com/callback/')

auth_props = f.get_authentication_tokens()
auth_url = auth_props['auth_url']

#Store this token in a session or something for later use in the next step.
oauth_token = auth_props['oauth_token']
oauth_token_secret = auth_props['oauth_token_secret']

print 'Connect with Flickr via: %s' % auth_url

Once you click "Allow" be sure that there is a URL set up to handle getting finalized tokens and possibly adding them to your database to use their information at a later date.

Handling the Callback

# oauth_token and oauth_token_secret come from the previous step
# if needed, store those in a session variable or something

f = FlickrAPI(api_key='*your app key*',
              api_secret='*your app secret*',
              oauth_token=oauth_token,
              oauth_token_secret=oauth_token_secret)

authorized_tokens = f.get_auth_tokens(oauth_verifier)

final_oauth_token = authorized_tokens['oauth_token']
final_oauth_token_secret = authorized_tokens['oauth_token_secret']

# Save those tokens to the database for a later use?

Getting the Users recent activity feed

# Get the final tokens from the database or wherever you have them stored

f = FlickrAPI(api_key='*your app key*',
              api_secret='*your app secret*',
              oauth_token=final_tokens['oauth_token'],
              oauth_token_secret=final_tokens['oauth_token_secret'])

recent_activity = f.get('flickr.activity.userComments')
print recent_activity

Add comment on a photo

# Assume you are using the FlickrAPI instance from the previous section

add_comment = f.post('flickr.photos.comments.addComment',
                     params={'photo_id': '6620847285', 'comment_text': 'This is a test comment.'})

#This returns the comment id if successful.
print add_comment

Remove comment on a photo

# Assume you are using the FlickrAPI instance from the previous section
# If the comment is already deleted, it will throw a FlickrAPIError (In this case, with code 2: Comment not found.)

del_comment = f.post('flickr.photos.comments.deleteComment', params={'comment_id':'45887890-6620847285-72157628767110559'})
print del_comment

Upload a photo

# Assume you are using the FlickrAPI instance from the previous section

files = open('/path/to/file/image.jpg', 'rb')
add_photo = f.post(params={'title':'Test Title!'}, files=files)

print add_photo  # Returns the photo id of the newly added photo

Catching errors

# Assume you are using the FlickrAPI instance from the previous section

try:
    # This comment was already deleted
    del_comment = f.post('flickr.photos.comments.deleteComment', params={'comment_id':'45887890-6620847285-72157628767110559'})
except FlickrAPIError, e:
    print e.msg
    print e.code
    print 'Something bad happened :('
Comments
  • Permissions problem with flickr.photosets.create (but not with uploading)

    Permissions problem with flickr.photosets.create (but not with uploading)

    I have included below the flask views I am using to upload and to create a set.

    The 2nd throws a 99 error code: "Insufficient permissions. Method requires write privileges; none granted." This is obviously a little confusing as it has just let me upload a photo with the same oauth tokens. I get the same error message if I try to create a comment.

    Any suggestions would be greatly appreciated, as otherwise your library has been nice and simple to get working!

    @app.route("/flickr/")
    def flickr_upload():
        f = flickr.FlickrAPI(api_key=api_key,
          api_secret=api_secret,
          oauth_token=escape(session['final_token']),
          oauth_token_secret=escape(session['final_secret']))
    
        photo_id = f.post(params={'title':'Testing API upload'}, files=open('/repos/flickrd/photo.jpg','rb'))
        return str(photo_id)
    
    @app.route("/flickr/set")
    def flickr_set():
        f = flickr.FlickrAPI(api_key=api_key,
          api_secret=api_secret,
          oauth_token=escape(session['final_token']),
          oauth_token_secret=escape(session['final_secret']))
    
        set_id = f.post('flickr.photosets.create', params={'title':'API set', 'primary_photo_id':'8514295132'})
        return str(set_id)
    
    opened by craigloftus 6
  • changed all endpoints to SSL

    changed all endpoints to SSL

    Flickr has enabled SSL on all of the API endpoints and later this year Flickr will be switching to SSL only endpoints. Source of the information: http://code.flickr.net/2014/02/24/new-ssl-endpoints-for-the-flickr-api/ Didn't see any issues while running my tests.

    Thanks,

    Sergey.

    opened by morozgrafix 4
  • modified passing of parameters in the POST portion of the Client.request method

    modified passing of parameters in the POST portion of the Client.request method

    since oauth2 discards parameters when the content type is JSON. I had to make this change in order to do POST for the flickr API method flickr.photosets.create (which is a POST with no data and a couple of required parameters). The flickr API was complaining that my request did not include those parameters and I found out that since the content type is JSON, when these parameters get passed to oauth2 client, they get dropped since oauth2 is only looking for parameters of application/x-www-form-urlencoded.

    opened by willtownes 3
  • Flickr API endpoint is going to be SSL only

    Flickr API endpoint is going to be SSL only

    Please note this Flickr announcement: http://code.flickr.net/2014/04/30/flickr-api-going-ssl-only-on-june-27th-2014/

    Flickr API endpoint is going to be SSL only. So flickr.FlickrAPI.api_base which has a value http://api.flickr.com/services needed to be changed to https://api.flickr.com/services.

    Besides, upload and replace URL also changed to https://up.flickr.com/services/upload/ and https://up.flickr.com/services/replace/ which has different domain.

    opened by toracle 2
  • Pip doesn't see the latest version

    Pip doesn't see the latest version

    In the version I got from pip, the post parameter issue that was fixed by will townes doesn't appear. I had to refix it :).

    Do you have to bump the version in the setup file or something so that pypy sees it?

    opened by rmoskal 2
  • API request works very slowly after upload a file

    API request works very slowly after upload a file

    I experienced API request works very slowly (20-30secs) after upload a file. Looking in the source code, I found suspicious code.

    When call api_request method with files, code sets Content-Length to the header, which is reused for further requests. So, the normal (not heavy uploading) get/post api requests are to have very large Content-Length header and make a server to wait for a long time.

    I tested the hypothesis with modifying source code to remove Content-Length key for self.header just after upload file, and it works well fast.

    So, please clear Content-Length header when upload is done. self.header is reused so it affects to further requests.

    opened by toracle 2
  • Flickr doesn't recognise the permission set - is the API working?

    Flickr doesn't recognise the permission set - is the API working?

    My users get the above error when clicking through on the generated auth url. Code:

        f = FlickrAPI(api_key=self.api_key,
            api_secret=self.api_secret,
            callback_url='http://url/oauthcallback')
    
        self.auth_props = f.get_authentication_tokens()
        self.auth_url = self.auth_props['auth_url']
    
        oauth_token_secret = self.auth_props['oauth_token_secret']
        self.context.setTempTokenSecret(self.request.principal.id,oauth_token_secret)
    

    Does the api work?

    opened by ghost 2
  • Flickr returns error on POST request without Content-Length in the headers (OS dependent)

    Flickr returns error on POST request without Content-Length in the headers (OS dependent)

    While running python-flickr from some *nix systems and making a POST request to Flickr API - Flickr will return non JSON page like this:

    screenshot 2014-06-01 22 21 33

    Same code works on OS X 10.9.X, but producing an error on RHEL or Ubuntu system. The reason why this is happening is that when Content-Length is not specified in the headers of the request, Flickr Apache Traffic Server will return HTTP/1.1 400 Content Length Required error and then redirect to page shown above.

    Here are some traces that I pulled by turning on httplib2 debugger on. (with my API info redacted):

    From OS X - works as expected:

    connect: (api.flickr.com, 443)
    send: 'POST /services/rest?api_key=<API_KEY>&nojsoncallback=1&method=flickr.photos.comments.addComment&format=json&comment_text=This+is+a+test+comment.&photo_id=14114731790 HTTP/1.1\r\nHost: api.flickr.com\r\nContent-Length: 0\r\ncontent-type: application/json\r\naccept-encoding: gzip, deflate\r\nauthorization: OAuth realm="https://api.flickr.com", oauth_body_hash="<OAUTH_BODY_HASH>", oauth_nonce="89465404", oauth_timestamp="1401523858", oauth_consumer_key="<API_KEY>", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="<OAUTH_TOKEN>", oauth_signature="<OAUTH_SIGNATURE>"\r\nuser-agent: Python-Flickr v0.3.0\r\n\r\n'
    reply: 'HTTP/1.1 200 OK\r\n'
    header: Date: Sat, 31 May 2014 08:10:58 GMT
    header: Content-Type: application/json
    header: Content-Length: 249
    header: P3P: policyref="http://info.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE LOC GOV"
    header: Cache-Control: private
    header: X-Served-By: www273.flickr.bf1.yahoo.com
    header: Vary: Accept-Encoding
    header: Content-Encoding: gzip
    header: Age: 0
    header: Via: http/1.1 fts106.flickr.bf1.yahoo.com (ApacheTrafficServer/4.0.2 [cMsSf ]), http/1.1 r04.ycpi.lax.yahoo.net (ApacheTrafficServer/4.0.2 [cMsSf ])
    header: Server: ATS
    header: Connection: keep-alive
    {'comment': {'permalink': 'https://www.flickr.com/photos/deadlypinkrhino/14114731790/#comment72157644519164118', 'realname': 'Deadly Pink Rhino', 'path_alias': 'deadlypinkrhino', 'author': '60941703@N06', 'datecreate': '1401496262', '_content': 'This is a test comment.', 'authorname': 'DeadlyPinkRhino', 'id': '60896381-14114731790-72157644519164118'}, 'stat': 'ok'}
    

    From Ubuntu:

    connect: (api.flickr.com, 443)
    send: 'POST /services/rest?api_key=<API_KEY>&nojsoncallback=1&method=flickr.photos.comments.addComment&format=json&comment_text=This+is+a+test+comment.&photo_id=14114731790 HTTP/1.1\r\nHost: api.flickr.com\r\ncontent-type: application/json\r\naccept-encoding: gzip, deflate\r\nauthorization: OAuth realm="https://api.flickr.com", oauth_body_hash="<OAUTH_BODY_HASH>", oauth_nonce="72642461", oauth_timestamp="1401523684", oauth_consumer_key="<API_KEY>", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="<OAUTH_TOKEN>", oauth_signature="<OAUTH_SIGNATURE>"\r\nuser-agent: Python-Flickr v0.3.0\r\n\r\n'
    reply: 'HTTP/1.1 400 Content Length Required\r\n'
    header: Date: Sat, 31 May 2014 08:08:04 GMT
    header: Connection: close
    header: Via: http/1.1 r15.ycpi.gq1.yahoo.net (ApacheTrafficServer/4.0.2 [c s f ])
    header: Server: ATS
    header: Cache-Control: no-store
    header: Content-Type: text/html; charset=utf-8
    header: Content-Language: en
    header: Content-Length: 1464
    Traceback (most recent call last):
      File "addComment_test.py", line 12, in <module>
        add_comment = flickr_api.post('flickr.photos.comments.addComment',params={'photo_id': '14114731790', 'comment_text': 'This is a test comment.'})
      File "/usr/local/lib/python2.7/dist-packages/flickr.py", line 317, in post
        return self.api_request(endpoint, method='POST', params=params, files=files, replace=replace)
      File "/usr/local/lib/python2.7/dist-packages/flickr.py", line 298, in api_request
        raise FlickrAPIError('Content is not valid JSON, unable to be decoded.')
    flickr.FlickrAPIError: 'Content is not valid JSON, unable to be decoded.'
    

    I already have a patch to correct this problem that I will be submitting and this is a result from the same system that used to surface this issue.

    connect: (api.flickr.com, 443)
    send: 'POST /services/rest?api_key=<API_KEY>&nojsoncallback=1&method=flickr.photos.comments.addComment&format=json&comment_text=This+is+a+test+comment.&photo_id=14114731790 HTTP/1.1\r\nHost: api.flickr.com\r\ncontent-length: 0\r\ncontent-type: application/json\r\naccept-encoding: gzip, deflate\r\nauthorization: OAuth realm="https://api.flickr.com", oauth_body_hash="<OAUTH_BODY_HASH>", oauth_nonce="55711331", oauth_timestamp="1401524098", oauth_consumer_key="<API_KEY>", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_token="<OAUTH_TOKEN>", oauth_signature="<OAUTH_SIGNATURE>"\r\nuser-agent: Python-Flickr v0.3.0\r\n\r\n'
    reply: 'HTTP/1.1 200 OK\r\n'
    header: Date: Sat, 31 May 2014 08:14:58 GMT
    header: Content-Type: application/json
    header: Content-Length: 249
    header: P3P: policyref="http://info.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE LOC GOV"
    header: Cache-Control: private
    header: X-Served-By: www223.flickr.bf1.yahoo.com
    header: Vary: Accept-Encoding
    header: Content-Encoding: gzip
    header: Age: 0
    header: Via: http/1.1 fts119.flickr.bf1.yahoo.com (ApacheTrafficServer/4.0.2 [cMsSf ]), http/1.1 r11.ycpi.sjb.yahoo.net (ApacheTrafficServer/4.0.2 [cMsSf ])
    header: Server: ATS
    header: Connection: keep-alive
    {u'comment': {u'permalink': u'https://www.flickr.com/photos/deadlypinkrhino/14114731790/#comment72157644519164118', u'realname': u'Deadly Pink Rhino', u'path_alias': u'deadlypinkrhino', u'author': u'60941703@N06', u'datecreate': u'1401496262', u'_content': u'This is a test comment.', u'authorname': u'DeadlyPinkRhino', u'id': u'60896381-14114731790-72157644519164118'}, u'stat': u'ok'}
    
    opened by morozgrafix 1
  • Error Getting Tokens

    Error Getting Tokens

    I receive an error when attempting to retrieve the tokens. I am passing the verifier to get_auth_tokens but receive this error:

    Traceback (most recent call last): File "harvest_flickr.py", line 26, in authorized_tokens = f.get_auth_tokens(oauth_verifier) File "/Users/Derrick/Development/harvest/flickr/flickr.py", line 189, in get_auth_tokens raise FlickrAuthError('Getting access tokens failed: %s Response Status' % resp['status']) flickr.flickr.FlickrAuthError: 'Getting access tokens failed: 400 Response Status'

    opened by DerrickLamers 1
  • abnormal behavior auth

    abnormal behavior auth

    Hi, I have a trouble but i don't know why i can generate auth_url then i can go to the url but when i click on 'Ok' some abnormal happen the url reload the authentification page and show the same page, but when i click 'ok' for second time flickr show me a message of error for oauth_token invalid. here is my code

    class Flickr(web.RequestHandler):
        def get(self):
            api_key = 'xx'
            api_secret = 'xxx'
            oauth_verifier = self.get_argument('oauth_verifier', None)
            if not oauth_verifier:
                f = FlickrAPI(api_key=api_key, api_secret=api_secret, callback_url='http://192.168.1.101:8080:8080/flickr/')
                auth_props = f.get_authentication_tokens(perms='read')
                self.set_secure_cookie('oauth_token', auth_props['oauth_token'])
                self.set_secure_cookie('oauth_token_secret', auth_props['oauth_token_secret'])
                self.redirect(auth_props['auth_url'])
            else:
                OAUTH_TOKEN = self.get_argument('oauth_token', None)
                OAUTH_TOKEN_SECRET = self.get_secure_cookie('oauth_token_secret')
                f = FlickrAPI(api_key=api_key, api_secret=api_secret,
                              oauth_token=OAUTH_TOKEN,
                              oauth_token_secret=OAUTH_TOKEN_SECRET)
                authorized_tokens = f.get_auth_tokens(oauth_verifier)
                final_oauth_token = authorized_tokens['oauth_token']
                final_oauth_token_secret = authorized_tokens['oauth_token_secret']
                f = FlickrAPI(api_key=api_key,
                              api_secret=api_secret,
                              oauth_token=final_oauth_token['oauth_token'],
                              oauth_token_secret=final_oauth_token_secret['oauth_token_secret'])
                u = f.get('flickr.urls.getUserProfile')
    
    opened by oamm 0
Owner
Mike Helmick
Mike Helmick
A Python Library to interface with Tumblr v2 REST API & OAuth

Tumblpy Tumblpy is a Python library to help interface with Tumblr v2 REST API & OAuth Features Retrieve user information and blog information Common T

Mike Helmick 125 Jun 20, 2022
Proxy server that records responses for UI testing (and other things)

Welcome to playback-proxy ?? A proxy tool that records communication (requests, websockets) between client and server. This recording can later be use

Yurii 41 Apr 1, 2022
This repository provides a set functions to extract paragraphs from AWS Textract responses.

extract-paragraphs-with-aws-textract Since AWS Textract (the AWS OCR service) does not have a native function to extract paragraphs, this repository p

Juan Anzola 3 Jan 26, 2022
Python bindings to the Syncthing REST interface.

python-syncthing Python bindings to the Syncthing REST interface. Python API Documentation Syncthing Syncthing REST Documentation Syncthing Forums $ p

Blake VandeMerwe 64 Aug 13, 2022
A Python script to create customised Spotify playlists using the JSON, Spotipy Library and Spotify Web API, based on seed tracks in your history.

A Python script to create customised Spotify playlists using the JSON, Spotipy Library and Spotify Web API, based on seed tracks in your history.

Youngseo Park 1 Feb 1, 2022
Python library for interacting with the Wunderlist 2 REST API

Overview Wunderpy2 is a thin Python library for accessing the official Wunderlist 2 API. What does a thin library mean here? Only the bare minimum of

mieubrisse 24 Dec 29, 2020
NiceHash Python Library and Command Line Rest API

NiceHash Python Library and Command Line Rest API Requirements / Modules pip install requests Required data and where to get it Following data is nee

Ashlin Darius Govindasamy 2 Jan 2, 2022
NiceHash Python Library and Command Line Rest API

NiceHash Python Library and Command Line Rest API Requirements / Modules pip install requests Required data and where to get it Following data is nee

Ashlin Darius Govindasamy 2 Jan 2, 2022
TM1py is a Python package that wraps the TM1 REST API in a simple to use library.

By wrapping the IBM Planning Analytics (TM1) REST API in a concise Python framework, TM1py facilitates Python developments for TM1. Interacting with T

Cubewise CODE 147 Dec 15, 2022
Python library wrapping and enhancing the Invenio RDM REST API.

Iridium The metal Iridium is used to refine and enhance metal alloys. Similarly, this package provides an enhanced coating around the Invenio RDM APIs

Materials Data Science and Informatics 2 Mar 29, 2022
A client library for the REST API of DocuWare's DMS

docuware-client This is a client library for the REST API of DocuWare DMS. Since DocuWare's documentation regarding the REST API is very sparse (at th

Stefan Schönberger 1 Feb 23, 2022
Python client for Invidious' JSON API

Python project template A template for new Python projects. Features Automatically builds PDoc documentation & uploads package to PyPI on new GitHub r

Kevo 2 Jun 5, 2022
NewpaperNews-API - Json data of the news with python

NewsAPI API Documentation BASE_URL = "https://saurav.tech/NewsAPI/" top_headline

Aryaman Prakash 2 Sep 23, 2022
A very simple Salesforce.com REST API client for Python

Simple Salesforce Simple Salesforce is a basic Salesforce.com REST API client built for Python 3.5, 3.6, 3.7 and 3.8. The goal is to provide a very lo

simple salesforce 1.4k Dec 29, 2022
📦 Opensource Python wrapper for Hiven's REST and WebSocket API

hiven.py ?? Opensource Python wrapper for Hiven's REST and WebSocket API Installation pip install -U hiven.py Usage hiven.py is currently under devel

Kevin Thomas 3 Sep 3, 2021
Python bindings for swm-core client REST API

Python bindings for swm-core client REST API Description Sky Port is an universal bus between user software and compute resources. It can also be cons

Sky Workflows 1 Jan 1, 2022
An unofficial Python wrapper for the 'Binance exchange REST API'

Welcome to binex_f v0.1.0 many interfaces are heavily used by myself in product environment, the websocket is reliable (re)connected. Latest version:

DeepLn 2 Jan 5, 2022
pyDuinoCoin is a simple python integration for the DuinoCoin REST API, that allows developers to communicate with DuinoCoin Master Server

PyDuinoCoin PyDuinoCoin is a simple python integration for the DuinoCoin REST API, that allows developers to communicate with DuinoCoin Main Server. I

BackrndSource 6 Jul 14, 2022
A simple waybar module to display the status of the ICE you are currently in using the ICE Portals JSON API.

waybar-iceportal A simple waybar module to display the status of the ICE you are currently in using the ICE Portals JSON API. Installation Ensure pyth

Moritz 7 Aug 26, 2022