Reputation: 35194
I just created an account on 500px.com, and would like to use their API: http://developer.500px.com/
But it looks like it cant return JSONP, only JSON.
Is there any way to make a php file that you can post a url to -> make it convert the response from the api from JSON to JSONP, so i can handle it on the client side?
I havent been writing any PHP in a long time, so any help is appreciated. Hope you get the idea, otherwise ill elaborate. Thanks
Upvotes: 1
Views: 3504
Reputation: 75317
Sure you can. The only difference between JSON and JSONP is that JSONP is wrapped with a function name;
{ "x": "hello" } // JSON
foo({ "x": "hello" }); // JSONP.
In it's simplest form you can end up with something like this;
<?php echo $_GET['callback']; ?>(<?php echo file_get_contents($_GET['endpoint']); ?>);
and you'd expect clients to use it like this;
http://yourserver.com/proxy.php?endpoint=https%3A%2F%2Fapi.500px.com%2Fv1%2Foauth%2Fauthorize&callback=foo
Note the encoded URL and the addition of the callback parameter to know which function to invoke.
Of course, you'll need to valid the input; check the existance of the parameters, check the endpoint
passed isn't malicious etc. You might want to also cache the responses on your server to stop you reaching any limits imposed on the API.
Something more resilient against malicious input could look like;
// checks for existence, and checks the input isn't an array
function getAsString($param) {
if (is_null($_GET[$param]) || !is_string($_GET[$param])) {
return '';
}
return $_GET[$param];
}
$endpoint = getAsString('endpoint');
// check callback is only alpha-numeric characters
$callback = preg_replace('/[^\w\d]/', '', getAsString('callback'));
// check the endpoint is for the 500px API
$is_api = (strpos($endpoint, 'https://api.500px.com') === 0);
if (strlen($callback) > 0 && $is_api) {
echo $callback . '(' . file_get_contents($endpoint) . ')'
} else {
// handle error
}
Upvotes: 5