Coder Social home page Coder Social logo

php-discogs-api's Introduction

Discogs Api

Build Status Latest Stable Version Total Downloads License Quality

This library is a PHP 5.4 implementation of the Discogs API v2.0. The Discogs API is a REST-based interface. By using this library you don't have to worry about communicating with the API: all the hard work has already be done.

This API is build upon the shoulders of a giant: Guzzle 4.0. This is an absolutely awesome library.

Deprecated

This repository is outdated and not maintained anymore. Please see https://github.com/calliostro/php-discogs-api for a more up to date version.

License

This library is released under the MIT license. See the complete license in the LICENSE file.

Installation

Start by installing composer. Next do:

$ composer require ricbra/php-discogs-api

Requirements

PHP >=5.4.0

Usage

Creating a new instance is as simple as:

<?php
$client = Discogs\ClientFactory::factory([]);

User-Agent

Discogs requires that you supply a User-Agent. You can do this easily:

<?php
$client = Discogs\ClientFactory::factory([
    'defaults' => [
        'headers' => ['User-Agent' => 'your-app-name/0.1 +https://www.awesomesite.com'],
    ]
]);

Throttling

Discogs doesn't like it when you hit their API at a too high connection rate. Use the ThrottleSubscriber to prevent getting errors or banned:

<?php

$client = Discogs\ClientFactory::factory();
$client->getHttpClient()->getEmitter()->attach(new Discogs\Subscriber\ThrottleSubscriber());

Authentication

Discogs API allow to access protected endpoints with either a simple Discogs Auth Flow or a more advanced (and more complex) Oauth Flow

Discogs Auth

As stated in the Discogs Authentication documentation:

In order to access protected endpoints, you’ll need to register for either a consumer key and secret or user token, depending on your situation:

  • To easily access your own user account information, use a User token.
  • To get access to an endpoint that requires authentication and build 3rd party apps, use a Consumer Key and Secret.

With the Discogs Php API you can add your credentials to each request by adding a query key to your own defaults like this:

$client = ClientFactory::factory([
    'defaults' => [
        'query' => [
            'key' => 'my-key',
            'secret' => 'my-secret',
        ],
    ]
]);

OAuth

There are a lot of endpoints which require OAuth. Lucky for you using Guzzle this is peanuts. If you're having trouble obtaining the token and token_secret, please check out my example implementation.

<?php

$client = Discogs\ClientFactory::factory([]);
$oauth = new GuzzleHttp\Subscriber\Oauth\Oauth1([
    'consumer_key'    => $consumerKey, // from Discogs developer page
    'consumer_secret' => $consumerSecret, // from Discogs developer page
    'token'           => $token['oauth_token'], // get this using a OAuth library
    'token_secret'    => $token['oauth_token_secret'] // get this using a OAuth library
]);
$client->getHttpClient()->getEmitter()->attach($oauth);

$response = $client->search([
    'q' => 'searchstring'
]);

History

Another cool plugin is the History plugin:

<?php

$client = Discogs\ClientFactory::factory([]);
$history = new GuzzleHttp\Subscriber\History();
$client->getHttpClient()->getEmitter()->attach($history);

$response = $client->search([
    'q' => 'searchstring'
]);

foreach ($history as $row) {
    print (string) $row['request'];
    print (string) $row['response'];
}

More info and plugins

For more information about Guzzle and its plugins checkout the docs.

Perform a search:

Per august 2014 a signed OAuth request is required for this endpoint.

<?php

$response = $client->search([
    'q' => 'Meagashira'
]);
// Loop through results
foreach ($response['results'] as $result) {
    var_dump($result['title']);
}
// Pagination data
var_dump($response['pagination']);

// Dump all data
var_dump($response->toArray());

Get information about a label:

<?php

$label = $service->getLabel([
    'id' => 1
]);

Get information about an artist:

<?php

$artist = $service->getArtist([
    'id' => 1
]);

Get information about a release:

<?php

$release = $service->getRelease([
    'id' => 1
]);

echo $release['title']."\n";

Get information about a master release:

<?php

$master  = $service->getMaster([
    'id' => 1
]);

echo $master['title']."\n";

Get image

Discogs returns the full url to images so just use the internal client to get those:

php

$release = $client->getRelease([
    'id' => 1
]);
foreach ($release['images'] as $image) {
    $response = $client->getHttpClient()->get($image['uri']);
    // response code
    echo $response->getStatusCode();
    // image blob itself
    echo $client->getHttpClient()->get($image['uri'])->getBody()->getContents();
}

User Collection

Authorization is required when folder_id is not 0.

Get collection folders

<?php

$folders = $service->getCollectionFolders([
    'username' => 'example'
]);

Get collection folder

<?php

$folder = $service->getCollectionFolder([
    'username' => 'example',
    'folder_id' => 1
]);

Get collection items by folder

<?php

$items = $service->getCollectionItemsByFolder([
    'username' => 'example',
    'folder_id' => 3
]);

Documentation

Further documentation can be found at the Discogs API v2.0 Documentation.

Contributing

Implemented a missing call? PR's are welcome!

Bitdeli Badge

php-discogs-api's People

Contributors

bitdeli-chef avatar digitalgrease avatar floydian77 avatar iamdey avatar korndoerfer avatar patrickbussmann avatar ricbra avatar thomasmery avatar ualinker 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  avatar  avatar  avatar  avatar  avatar  avatar

php-discogs-api's Issues

Problems since Discogs` switch to https

This might not be a problem with this library, but maybe somebody here knows what goes wrong here:. I get this error when I use the getRelease call of the API. I get similar errors on other calls as well. Anybody know what is going on? I read on the Discogs forum that they switched to https only yesterday. My Api is configured to call https://api.discogs.com already.

Error executing command: cURL error 35: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
Test case: ProductTest(testImportImportedDiscogsRelease)
Stack trace:
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/command/src/AbstractClient.php : 253
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/Event/Emitter.php : 109
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/RequestFsm.php : 140
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/RequestFsm.php : 132
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/react/promise/src/FulfilledPromise.php : 25
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/ringphp/src/Future/CompletedFutureValue.php : 55
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/Message/FutureResponse.php : 43
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/RequestFsm.php : 135
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/RequestFsm.php : 132
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/react/promise/src/FulfilledPromise.php : 25
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/ringphp/src/Future/CompletedFutureValue.php : 55
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/Message/FutureResponse.php : 43
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/RequestFsm.php : 135
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/guzzle/src/Client.php : 165
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/command/src/AbstractClient.php : 88
/Users/uscreen/Sites/buyreggae-2.0/app/Vendor/guzzlehttp/command/src/AbstractClient.php : 76
/Users/uscreen/Sites/buyreggae-2.0/app/Test/Case/Model/ProductTest.php : 275

Bump into php-7.1+ versions

As title, the php-7.1 versions have been released for the while.

And I think it's time to consider bumping into the php-7.1+ versions now.

To do this issue, I think we should consider following points:

  • Upgrade the necessary dependencies to the current released versions. Such as Guzzle.
  • Checking the syntax and modify them to be compatible with the php-7.1+ versions.

getImage with new fully qualified URLs

Hello,
I have been struggling with this for a while and am unable to come to a resolution myself, so I am hoping you are able to help. Discogs switched to fully qualified URLs a while ago, and I cannot seem to be able to get the getImage operation to succeed. I have changed the base URL in service.php to blank, and changed the getImage operations to:
'getImage' => [ 'httpMethod' => 'GET', 'uri' => '{filename}', 'responseModel' => 'GetImage', 'parameters' => [ 'filename' => [ 'type' => 'string', 'location' => 'uri', 'required' => true ] ] ],
I am using the following code to call the getImage operation:
$img = $client->getImage([ 'filename' => $imgurl ]);
where $imgurl is something like 'https://api-img.discogs.com/h5jo0FYxTiv0kE6vnKBbpJ5_oyM=/fit-in/600x594/filters:strip_icc():format(jpeg):mode_rgb():quality(90)/discogs-images/R-3031242-1312599382.jpeg.jpg'.

But I keep getting the error

Catchable fatal error: Argument 4 passed to GuzzleHttp\Command\Guzzle\Subscriber\ProcessResponse::visitOuterObject() must implement interface GuzzleHttp\Message\ResponseInterface, null given, called in C:\wamp\www\Viscogs\vendor\guzzlehttp\guzzle-services\src\Subscriber\ProcessResponse.php on line 106 and defined in C:\wamp\www\Viscogs\vendor\guzzlehttp\guzzle-services\src\Subscriber\ProcessResponse.php on line 148

All other requests such as getRelease and getOAuthIdentity are working just fine. What is it about getImage that is causing it to fail? I have been struggling with this and hope it may be easy for you to see what is wrong. Please let me know if you need any further information to help troubleshoot the problem.

Thank you!

oauth actually working?

I've obtained an access token + secret from discogs but can't seem to get the following working altough it does work with other (more complicated) clients:

$client = Discogs\ClientFactory::factory([
    'defaults' => [
        'headers' => ['User-Agent' => 'diskollect/0.1 +http://beta.diskollect.com'],
    ]
]);

$oauth = new GuzzleHttp\Subscriber\Oauth\Oauth1([
    'consumer_key'    => $_ENV['DC_CONSUMER_KEY'], // from Discogs developer page
    'consumer_secret' => $_ENV['DC_CONSUMER_SECRET'], // from Discogs developer page
    'token'           => $user->discogs_access_token, // valid
    'token_secret'    => $user->discogs_access_token_secret // valid
]);
$client->getHttpClient()->getEmitter()->attach($oauth);

$identity = $client->getOAuthIdentity();

following exception is thrown:

GuzzleHttp \ Command \ Exception \ CommandClientException
Error executing command: Client error response [url] http://api.discogs.com/oauth/identity [status code] 401 [reason phrase] Unauthorized

So after reading the https://github.com/guzzle/oauth-subscriber instructions I added the ['auth' => 'oauth'] param to the getOAuthIdentity method in service.php:

'getOAuthIdentity' => [
    'httpMethod' => 'GET',
    'uri' => 'oauth/identity',
    'responseModel' => 'GetResponse',
    'auth' => 'oauth',
]

But still no luck. The oauth object itself is filled with the correct values. I'm using Laravel as a framework. I'm not sure if I'm doing something wrong here. Any ideas?

Consider modifying example to include inline auth

Discogs also supports authentication via inline auth in the http request. For my own purposes I didn't need full OAuth and struggled to get it working, so inline auth via the personal access token was enough to get the data I needed.

As per the developer doc a request like this works, replacing the token with your personal access token:
curl "https://api.discogs.com/database/search?q=Nirvana&token=abcxyz123456"

You can add additional defaults when creating the client, or modify the php-discogs-api\lib\Discogs\ClientFactory.php defaults section to include the below to add the token to every request.
'query' => ['token' => 'YOURTOKENHERE']

This may help others wishing to deploy your code but not needing full OAuth :)

Token & token?

Hi there!

Totally new to both Oauth and Guzzle and having issues with these 2 lines in your example.
https://github.com/ricbra/php-discogs-api#oauth

‘token’ => $token[‘oauth_token’], // get this using a OAuth library
‘token_secret’ => $token[‘oauth_token_secret’] // get this using a OAuth library

How does the tokens work? I know I can get one from my Discogs developer admin but it doesn't work?

Need this to loop out album covers from a marketplace.
That aside, thanks for a nice library!

PEACE

package combination

HI there,
At first thanks for this awesome package :-).

I'm trying to get this package with "robbiep/cloudconvert-laravel" to work. But this package needs "guzzlehttp/guzzle": "~5.0".

Sadly php-discogs-api has a dependency for "guzzlehttp/guzzle": "~4.0", so it seems that these 2 packages are not compatible.

Is it planned to update this package to work with guzzle 5.0 ?

Best Regards

result of artist/XX/releases

Hi,

I use the API lib with your bundle wrapper in SF2.

When I try to get the releases http://api.discogs.com/artists/45/releases for example.

Before the transformation from standard class to model I have this :

object(stdClass)[207]
  public 'pagination' => 
    object(stdClass)[245]
      public 'per_page' => int 50
      public 'pages' => int 15
      public 'page' => int 1
      public 'urls' => 
        object(stdClass)[246]
          public 'last' => string 'http://api.discogs.com/artists/45/releases?per_page=50&page=15' (length=62)
          public 'next' => string 'http://api.discogs.com/artists/45/releases?per_page=50&page=2' (length=61)
      public 'items' => int 706
  public 'releases' => 
    array (size=50)
      0 => 
        object(stdClass)[247]
          public 'thumb' => string 'http://api.discogs.com/image/R-150-63114-1148806222.jpeg' (length=56)
          public 'title' => string 'Analog Bubblebath Vol 2' (length=23)
          public 'main_release' => int 63114
          public 'artist' => string 'Aphex Twin' (length=10)
          public 'role' => string 'Main' (length=4)
          public 'year' => int 1991
          public 'resource_url' => string 'http://api.discogs.com/masters/258478' (length=37)
          public 'type' => string 'master' (length=6)
          public 'id' => int 258478
      1 => 
.....

but as result I have only the pagination when I call like this in my controller :

$discogs = $this->container->get('discogs');
$release  = $discogs->getReleases(45);

I only get the pagination and not the releases.

object(Discogs\Model\Resultset)[299]
  protected 'pagination' => 
    object(Discogs\Model\Pagination)[303]
      protected 'perPage' => int 50
      protected 'items' => int 706
      protected 'page' => int 1
      protected 'urls' => 
        object(Discogs\Model\Urls)[310]
          protected 'last' => string 'http://api.discogs.com/artists/45/releases?per_page=50&page=15' (length=62)
          protected 'next' => string 'http://api.discogs.com/artists/45/releases?per_page=50&page=2' (length=61)
          protected 'previous' => null
          protected 'first' => null
      protected 'pages' => int 15
  protected 'results' => null

I think it's because of the ResultSet class which is used and doesn't have a setReleases method.

Hope this help.

I added the getImage operation, couln't make a working Guzzle model for receiving binary image data

Part of service.php

An attempt to describe the getImage operation for Discogs and the response model (based on Discogs API: Images).

It requires an OAuth token (tested after successful authentification).

// ...
,
        'getImage' => [
            'httpMethod' => 'GET',
            'uri' => 'images/{filename}',
            'responseModel' => 'GetImage',
            'parameters' => [
                'filename' => [
                    'type' => 'string',
                    'location' => 'uri',
                    'required' => true
                ]
            ]
        ]
    ],
    'models' => [
        'GetResponse' => [
            'type' => 'object',
            'additionalProperties' => [
                'location' => 'json'
            ],
        ],
        'GetImage' => [
            'type' => 'object',
            'additionalProperties' => [
                'location' => 'body'
            ],
        ]
    ]
];

Problem with search

Hello!

I am trying to use your library and specifically the search functionality. If i execute the following:

$discogs = new \Discogs\Service();
$resultSet = $discogs->search(array('q' => "1982 (Statik Selektah & Termanology) - 2012", 'type' => 'release'));

then the $resultsSet->results is empty. If i just copy paste the query '1982 (Statik Selektah & Termanology) - 2012' inside the search box at discogs.com then it returns the release i am looking for.

Am I using it correctly? Is there a better way?

Thank you for your time

Requesting Images

Hi ricbra!
Your lib works great! is it somehow possible to embed images with your api?

Thanks!

stefan

How to create $services object?

Hi there,

Thanks for this module!
Can you please let me know how can I create $services object to access method:

$release = $service->getRelease([
    'id' => 1
]);

Labels releases

Hi there - is it possible to add a feature to get all a labels releases? Cheers!

getImage sends 404 Not Found

I receive a [status code] 404 [reason phrase] Not Found, using getImage.

[url] http://api.discogs.com/images/R-5840514-1404162639-4473.jpeg.jpg [status code] 404 

When i send a request using getRelease i can see images passed using a different url like:
http://api-img.discogs.com/{....}

Seems like a discogs change in API. Can be this OAuth related?

Thanks.

GetInventory : per_page not working

The per_page parameter doesn't work in the GetInventory function.

public function testGetInventory()
    {
        $client = $this->createClient('get_inventory', $history = new History());
        $response = $client->getInventory([
            'username'      => '360vinyl',
            'per_page'      => 100,
            'sort'          => 'price',
            'sort_order'    => 'asc'
        ]);

        $this->assertArrayHasKey('pagination', $response);
        $this->assertArrayHasKey('listings', $response);
        $this->assertCount(100, $response['listings']);
        $this->assertSame('GET', $history->getLastRequest()->getMethod());
        $this->assertSame('https://api.discogs.com/users/360vinyl/inventory?sort=price&sort_order=asc', $history->getLastRequest()->getUrl());
    }

Phpunit result :

PHPUnit 4.8.36 by Sebastian Bergmann and contributors.

.............F...........

Time: 2.7 seconds, Memory: 10.00MB

There was 1 failure:

1) Discogs\Test\ClientTest::testGetInventory
Failed asserting that actual size 50 matches expected size 100.

/home/clement/test_php_discogs/php-discogs-api/tests/Discogs/Test/ClientTest.php:197
/usr/share/php/PHPUnit/TextUI/Command.php:186
/usr/share/php/PHPUnit/TextUI/Command.php:138

FAILURES!
Tests: 25, Assertions: 113, Failures: 1.

Do you have an idea why it is not working ?

Thanks

Clement

'GuzzleHttp\Client'

Fatal error: Class 'GuzzleHttp\Client' not found in /home1/dnguah/public_html/instgram/php-discogs-api/lib/Discogs/ClientFactory.php on line 24

chaining api : label > releases > artist

first : thank you for this cool lib & bundle :)

Well I want to chain apis but it seems to be not allowed without overriding things. Basically this is what I may want to do (Am I wrong ?) :

$service = new \Discogs\Service; 
$label = $service->getLabel($n);
foreach ($label->getReleasesUrl() as $releaseUrl) {
    //not really optimized :s 
    //this call method is protected
    $release = $service->call($releaseUrl);
    //...
}

May be this can be related to #7

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.