flickr

package module
v0.0.0-...-0e47a65 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 23, 2021 License: MIT Imports: 27 Imported by: 0

README

flickr

A go library to easily consume Flickr API. The project is currently under heavy development, so it hasn't a version number yet.

GoDoc Build Status Coverage Status

Usage

flickr aims to expose a Go Api matching Flickr REST Api, so that you don't need to build HTTP requests and parse HTTP response manually. For example, the Flickr method flickr.photosets.create is implemented with the Create function in the flickr/photosets package:

import "fmt"
import "github.com/denmark/flickr"
import "github.com/denmark/flickr/photosets"

// create an API client with credentials
client := flickr.NewFlickrClient("your_apikey", "your_apisecret")
client.OAuthToken = "your_token"
client.OAuthTokenSecret = "your_tokenSecret"

response, _ := photosets.Create(client, "My Set", "Description", "primary_photo_id")
fmt.Println("New photoset created:", response.Photoset.Id)

flickr responses implement flickr.FlickrResponse interface. A response contains error codes and error messages (if any) produced by Flickr or the specific data returned by the api call. Different methods may return different kind of responses.

Upload a photo

There are a number of functions that don't map any actual Flickr Api method (see below for the detailed list). For example, to upload a photo, you call the UploadFile or UploadReader functions in the flickr package:

import "github.com/denmark/flickr"


// upload the image file with default (nil) options
resp, err := flickr.UploadFile(client, "/path/to/image", nil)

Files are uploaded through an io.Pipe fueled in a separate goroutine, so the process is pretty efficient.

Authentication (or how to retrieve OAuth credentials)

Several api calls must be authenticated and authorized: flickr only supports OAuth since the original token-based method has been deprecated by Flickr. This is an example describing the OAuth worflow from a command line application:

import "github.com/denmark/flickr"

client := flickr.NewFlickrClient("your_apikey", "your_apisecret")

// first, get a request token
requestTok, _ := flickr.GetRequestToken(client)

// build the authorizatin URL
url, _ := flickr.GetAuthorizeUrl(client, requestTok)

// ask user to hit the authorization url with
// their browser, authorize this application and coming
// back with the confirmation token

// finally, get the access token, setup the client and start making requests
accessTok, err := flickr.GetAccessToken(client, requestTok, "oauth_confirmation_code")
client.OAuthToken = accessTok.OAuthToken
client.OAuthTokenSecret = accessTok.OAuthTokenSecret
Api coverage

Only a small part of the Flickr Api is implemented as Go functions: even if it's quite simple to write the code for the mapping, I only did it for methods I actually need in my projects (contributions well accepted). Anyway, if you need to call a Flickr Api method that wasn't already mapped, you can do it manually:

import "fmt"
import "github.com/denmark/flickr"

client := flickr.NewFlickrClient("your_apikey", "your_apisecret")
client.Init()
client.Args.Set("method", "flickr.cameras.getBrandModels")
client.Args.Set("brand", "nikon")

client.OAuthSign()
response := &flickr.BasicResponse{}
err := flickr.DoGet(client, response)

if err != nil {
    fmt.Printf("Error: %s", err)
} else {
    fmt.Println("Api response:", response.Extra)
}

Checkout the example folder and the docs pages for more details.

Note on Go versions

The latest version v2 only supports go 1.6 and above, for Go < 1.6 use the v1 package:

go get gopkg.in/masci/flickr.v1

API Methods

Extra-API Methods

These are methods that are not actually part of the Flickr API

  • Get OAuth request token
  • Get OAuth authorize URL
  • Get OAuth access token
  • Upload photo
auth.oauth
  • flickr.auth.oauth.checkToken
photos
  • flickr.photos.delete
  • flickr.photos.getInfo
  • flickr.photos.setDates
photosets
  • flickr.photosets.addPhoto
  • flickr.photosets.create
  • flickr.photosets.delete
  • flickr.photosets.editMeta
  • flickr.photosets.editPhotos
  • flickr.photosets.getInfo
  • flickr.photosets.getList
  • flickr.photosets.getPhotos
  • flickr.photosets.orderSets
  • flickr.photosets.removePhoto
  • flickr.photosets.removePhotos
  • flickr.photosets.reorderPhotos
  • flickr.photosets.setPrimaryPhoto
people
  • flickr.people.getPhotos
test
  • flickr.test.echo
  • flickr.test.login
  • flickr.test.null

Documentation

Overview

Flickr.go is a Go library for accessing Flickr API https://www.flickr.com/services/api

Index

Constants

View Source
const (
	API_ENDPOINT      = "https://api.flickr.com/services/rest"
	UPLOAD_ENDPOINT   = "https://up.flickr.com/services/upload/"
	AUTHORIZE_URL     = "https://www.flickr.com/services/oauth/authorize"
	REQUEST_TOKEN_URL = "https://www.flickr.com/services/oauth/request_token"
	ACCESS_TOKEN_URL  = "https://www.flickr.com/services/oauth/access_token"
)

Variables

This section is empty.

Functions

func AssertParamsInBody

func AssertParamsInBody(t *testing.T, client *FlickrClient, params []string)

TODO

func DoGet

func DoGet(client *FlickrClient, r FlickrResponse) error

Perform a GET request to the Flickr API with the configured FlickrClient passed as first parameter. Results will be unmarshalled to fill in a FlickrResponse struct passed as second parameter.

func DoPost

func DoPost(client *FlickrClient, r FlickrResponse) error

Perform a POST request to the Flickr API with the configured FlickrClient, dumping client Args into the request Body.

func DoPostBody

func DoPostBody(client *FlickrClient, body *bytes.Buffer, bodyType string, r FlickrResponse) error

Perform a POST request to the Flickr API with the configured FlickrClient, the request body and the body content type. Results will be unmarshalled in a FlickrResponse struct.

func Expect

func Expect(t *testing.T, a interface{}, b interface{})

func FlickrMock

func FlickrMock(code int, body string, contentType string) (*httptest.Server, *http.Client)

func GetAuthorizeUrl

func GetAuthorizeUrl(client *FlickrClient, reqToken *RequestToken) (string, error)

Returns the URL users need to reach to grant permission to our application

Types

type BasicResponse

type BasicResponse struct {
	XMLName xml.Name `xml:"rsp"`
	// Status might contain "fail" or "ok" strings
	Status string `xml:"stat,attr"`
	// Flickr API error detail
	Error struct {
		Code    int    `xml:"code,attr"`
		Message string `xml:"msg,attr"`
	} `xml:"err"`
	Extra string `xml:",innerxml"`
}

Base type representing responses from Flickr API

func (*BasicResponse) ErrorCode

func (r *BasicResponse) ErrorCode() int

Return the error code (0 if no errors)

func (*BasicResponse) ErrorMsg

func (r *BasicResponse) ErrorMsg() string

Return error message string (empty string if no errors)

func (*BasicResponse) HasErrors

func (r *BasicResponse) HasErrors() bool

Return whether a response contains errors

func (*BasicResponse) SetErrorCode

func (r *BasicResponse) SetErrorCode(code int)

Set error code explicitly

func (*BasicResponse) SetErrorMsg

func (r *BasicResponse) SetErrorMsg(msg string)

Set error message explicitly

func (*BasicResponse) SetErrorStatus

func (r *BasicResponse) SetErrorStatus(hasErrors bool)

Set error status explicitly

type FakeBody

type FakeBody struct {
	// contains filtered or unexported fields
}

A ReaderCloser to fake http.Response Body field

func NewFakeBody

func NewFakeBody(s string) *FakeBody

func (FakeBody) Close

func (f FakeBody) Close() error

func (*FakeBody) Read

func (f *FakeBody) Read(p []byte) (n int, err error)

type FlickrClient

type FlickrClient struct {
	// Flickr application api key
	ApiKey string
	// Flickr application api secret
	ApiSecret string
	// A generic HTTP client to perform GET and POST requests
	HTTPClient *http.Client
	// The base url for API endpoints
	EndpointUrl string
	// A string containing POST or GET, needed for OAuth signing
	HTTPVerb string
	// A set of url params to query the API
	Args url.Values
	// User access token
	OAuthToken string
	// User secret token
	OAuthTokenSecret string
	// User flickr ID
	Id string
}

An utility type to wrap all resources and data needed to complete requests to the Flickr API

func GetTestClient

func GetTestClient() *FlickrClient

testing keys were published at http://www.wackylabs.net/2011/12/oauth-and-flickr-part-2/

func NewFlickrClient

func NewFlickrClient(apiKey string, apiSecret string) *FlickrClient

Create a Flickr client, apiKey and apiSecret are mandatory

func (*FlickrClient) ApiSign

func (c *FlickrClient) ApiSign()

Specific signing process for API calls: not the same as OAuth sign, used for requests that don't need user authorizations.

func (*FlickrClient) ClearArgs

func (c *FlickrClient) ClearArgs()

Remove all query params

func (*FlickrClient) GetUrl

func (c *FlickrClient) GetUrl() string

Evaluate the complete URL to make requests (base url + params)

func (*FlickrClient) Init

func (c *FlickrClient) Init()

Reset Args and set the default endpoint

func (*FlickrClient) OAuthSign

func (c *FlickrClient) OAuthSign()

Sign the request with a default set of OAuth parameters, needed to authorize users for certain writing/destructive operations.

func (*FlickrClient) SetOAuthDefaults

func (c *FlickrClient) SetOAuthDefaults()

Set the mandatory params for an OAuth request

func (*FlickrClient) Sign

func (c *FlickrClient) Sign(tokenSecret string)

Sign the next request performed by the FlickrClient

type FlickrResponse

type FlickrResponse interface {
	HasErrors() bool
	ErrorCode() int
	ErrorMsg() string
	SetErrorStatus(bool)
	SetErrorCode(int)
	SetErrorMsg(string)
}

Interface for Flickr request objects

type OAuthToken

type OAuthToken struct {
	// OAuth access token
	OAuthToken string
	// OAuth access token secret
	OAuthTokenSecret string
	// Flickr ID of token's owner
	UserNsid string
	// Flickr Username of token's owner
	Username string
	// Flickr full name of token's owner
	Fullname string
	// OAuth failing reason in case of errors
	OAuthProblem string
}

Type representing a OAuth access token along with its owner's data

func GetAccessToken

func GetAccessToken(client *FlickrClient, reqToken *RequestToken, oauthVerifier string) (*OAuthToken, error)

Get an access token providing an OAuth verifier provided by Flickr once the user authorizes your application

func ParseOAuthToken

func ParseOAuthToken(response string) (*OAuthToken, error)

Extract a OAuthToken from the response body

type RequestToken

type RequestToken struct {
	// Whether the callback url matches the one provided in Flickr dashboard
	OauthCallbackConfirmed bool
	// Request token
	OauthToken string
	// Request token secret
	OauthTokenSecret string
	// OAuth failing reason in case of errors
	OAuthProblem string
}

Type representing a request token during the exchange process

func GetRequestToken

func GetRequestToken(client *FlickrClient) (*RequestToken, error)

Retrieve a request token: this is the first step to get a fully functional access token from Flickr

func ParseRequestToken

func ParseRequestToken(response string) (*RequestToken, error)

Extract a RequestToken from the response body

type RewriteTransport

type RewriteTransport struct {
	Transport http.RoundTripper
	URL       *url.URL
}

mock the Flickr API

func (RewriteTransport) RoundTrip

func (t RewriteTransport) RoundTrip(req *http.Request) (*http.Response, error)

type UploadParams

type UploadParams struct {
	Title, Description           string
	Tags                         []string
	IsPublic, IsFamily, IsFriend bool
	ContentType                  int
	Hidden                       int
	SafetyLevel                  int
}

UploadParams is a convenience struct wrapping all optional upload parameters

func NewUploadParams

func NewUploadParams() *UploadParams

NewUploadParams provides meaningful default values

type UploadResponse

type UploadResponse struct {
	BasicResponse
	ID string `xml:"photoid"`
}

UploadResponse is a type representing a successful upload response from the api

func UploadFile

func UploadFile(client *FlickrClient, path string, optionalParams *UploadParams) (*UploadResponse, error)

UploadFile performs a file upload using the Flickr API. If optionalParams is nil, no parameters will be added to the request and Flickr will set User's default preferences. This call must be signed with write permissions

func UploadReader

func UploadReader(client *FlickrClient, photoReader io.Reader, name string, optionalParams *UploadParams) (*UploadResponse, error)

UploadReader does same as UploadFile but the photo file is passed as an io.Reader instead of a file path

func UploadReaderWithClient

func UploadReaderWithClient(client *FlickrClient, photoReader io.Reader, name string, optionalParams *UploadParams, httpClient *http.Client) (*UploadResponse, error)

UploadReaderWithClient does same as UploadReader but allows passing a custom httpClient

Directories

Path Synopsis
auth
oauth
Package implementing methods: flickr.auth.oauth.*
Package implementing methods: flickr.auth.oauth.*
Flickr.go error system
Flickr.go error system
examples
Package implementing methods: flickr.photosets.*
Package implementing methods: flickr.photosets.*
Package implementing methods: flickr.test.*
Package implementing methods: flickr.test.*

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL