0

Trying to retrieve some info from the Discogs API but I'm getting "Bad Request" every time I hit it programmatically.

If I run the same url in the browser it works just fine, but as they require a User-Agent string to be specified in the request this causes file_get_contents to understandably throw this error.

So I've written a function that I thought would handle this is below, but I 'm still getting the "Bad Request" errror :

$consumer_key = getenv('DISCOGS_CONSUMER_KEY');
$secret_key   = getenv('DISCOGS_CONSUMER_SECRET');
$options      = array('http' => array('user_agent' => 'Example/alpha +https://example.com'));
$context      = stream_context_create($options);
$results      = file_get_contents('https://api.discogs.com/database/search?q='.$term.'&key='.$consumer_key.'&secret='.$secret_key.'&per_page=10', false, $context);

Am I doing this wrong?

How do I specify a user-agent when issuing a file_get_contents request?

EDIT

I've just tried this using cURL and I'm getting the exact same 400 response :

$url = 'https://api.discogs.com/database/search?q='.$term.'&key='.$consumer_key.'&secret='.$secret_key.'&per_page=10';
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Example/alpha +https://example.com');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close ($ch);
die($output); // 400 "Bad Request"

What voodoo are these guys employing?

spice
  • 1,442
  • 19
  • 35

1 Answers1

0

After much messing around I finally cracked it, you have to specify your agent name in CURLOPT_ENCODING too.

Couldn't get file_get_contents working no matter what I tried but cURL is working now.

Hope it helps somebody.

Full example :

$url = 'https://api.discogs.com/database/search?q='.$term.'&key='.$consumer_key.'&secret='.$secret_key.'&per_page=10';
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Example/alpha +https://example.com');
curl_setopt($ch, CURLOPT_ENCODING, 'Example/alpha +https://example.com');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close ($ch);

// Then do whatever you wish with $output
spice
  • 1,442
  • 19
  • 35