Soundcloud API doesn't explicitly support pagination with json - json

Specific example I was working with:
http://api.soundcloud.com/users/dubstep/tracks.json?client_id=YOUR_CLIENT_ID
You'll get their first 50 tracks, but there is not next-href object like what you see in the xml version.
However, you can use offset and limit and it works as expected- but then I would need to "blindly" crawl through tracks until there are no more tracks, unlike with the XML version which gives you the "next page" of results. I wouldn't have even noticed it was paginated except by chance when I was searching the json object and noticed there was exactly 50 tracks (which is suspiciously even).
Is there a plan to support the next-href tag in json? Am I missing something? is it a bug that it's missing?

There is an undocumented parameter you can use linked_partitioning=1, that will add next_href to the response.
http://api.soundcloud.com/users/dubstep/tracks.json?client_id=YOUR_CLIENT_ID&linked_partitioning=1

for ex :
// build our API URL
$clientid = "Your API Client ID"; // Your API Client ID
$userid = "/ IDuser"; // ID of the user you are fetching the information for
// Grab the contents of the URL
//more php get
$number="1483";
$offset=1300;
$limit=200;
$soundcloud_url = "http://api.soundcloud.com/users/{$userid}/tracks.json?client_id={$clientid}&offset={$offset}&limit={$limit}";
$tracks_json = file_get_contents($soundcloud_url);
$tracks = json_decode($tracks_json);
foreach ($tracks as $track) {
echo "<pre>";
echo $track->title . ":";
echo $track->permalink_url . "";
echo "</pre>";
}

sI've seen this code is supposed to help (this is in Ruby):
# start paging through results, 100 at a time
tracks = client.get('/tracks', :order => 'created_at', :limit => page_size,
:linked_partitioning => 1)
tracks.each { |t| puts t.title }
However, the first set of results will show and i'll even see the "next_href" at the end of the response, but what are you supposed to do, to make the next set of results show?

Related

GetStream Laravel - Cannot batchadd to notification

I can't seem to use the batcher to copy an activity to notifications. I read from the docs
that there is a 100 limit to the TO field for copying activities, so i tried out using the batcher. but it does'nt seem to work. did I miss out something on the docs or on my code? if so, how do I get over the 100 limit?
$evtConvMention = array();
$evtConvMention[] = "event:{$event->id}";
$evtConvMention[] = "notification:1";
$evtConvMention[] = "notification:2";
$batcher = FeedManager::getClient()->batcher();
$batcher->addToMany([
"actor" => "App\User:{$user->id}",
"verb" => "eventpost",
"object" => "App\EventConversation:{$post->id}",
"foreign_id" => "App\EventConversation:{$post->id}"
], $evtConvMention);
The addToMany() call will have a similar limit. While I look into the PHP library a little more, it might be easier to use the To field in the activity payload itself.
$feed = FeedManager::getClient()->feed("event", $event->id);
$now = new \DateTime("now", new \DateTimeZone('Pacific/Nauru'));
$data = [
"actor" => "App\User:{$user->id}",
"verb" => "eventpost",
"object" => "App\EventConversation:{$post->id}",
"foreign_id" => "App\EventConversation:{$post->id}",
"time" => $now
];
$feed->addActivity($data);
We also HIGHLY recommend sending your own foreign_id and time fields in the payload as well (I've added an idea for the $now value in the code above, otherwise every feed will get its own unique record, which are a limited resource on your account.
If you have more than 100 notification feeds to write this into, it might be better to have the notification feeds for those users 'follow' the event feed. Then you don't need to use the to field at all.

Using Dancer2::Plugin::DBIC to pull values from database

I have a webapp where a user can log in and see a dashboard with some data. I'm using APIary for mock data and in my Postgres Database each of my users have an ID. These ID's are also used in the APIary JSON file with relevant information.
I'm using REST::Client and JSON to connect so for example the url for the user's dashboard is: "/user/dashboard/12345" (in Apiary)
and in the database there is a user with the ID "12345".
How can I make it so when the user logs in, their ID is used to pull the data that is relevant to them? (/user/dashboard/{id})? Any documentation or advice would be much appreciated!
The docs of Dancer2::Plugin::Auth::Extensible are showing one part of what you need to do already. In short, save the user ID in the session. I took part of code in the doc and added the session.
post '/login' => sub {
my ($success, $realm) = authenticate_user(
params->{username}, params->{password}
);
if ($success) {
# we are saving your user ID to the session here
session logged_in_user => params->{username};
session logged_in_user_realm => $realm;
} else {
# authentication failed
}
};
get '/dashboard' => sub {
my $client = REST::Client->new();
# ... and now we use the user ID from the session to get the
# from the webservice
$client->GET( $apiary . '/user/dashboard/' . session('logged_in_user') );
my $data = $client->responseContent();
# do stuff with $data
};
For those who want to know what I ended up doing:
Dancer2::Plugin::Auth::Extensible has
$user = logged_in_user();
When I printed this it showed me a hash of all the values that user had in the database including the additional ID I had. So I accessed the id with
my $user_id = $user->{user_id};
And appended $user_id to the end of the url!

Wordpress API JSON return limit

This is a simple question regarding Wordpress API /wp-json. I am querying some data filtered with certain category in Wordpress. My questions is how can I control amount of result that gets returned from my Get request... The default returns seems to return around 11 most recent results. Is there any way I can make it return only 1 (most recent), or like 100 posts. What is the minimum and maximum amount I can return. And what is the syntax for it. This is the default request I have:
http://thisismywebsitewherewordpresslives.com/wp-json/posts?fiter[category_name]=Some Category Name I want to query&filter[order]=ASC
If you're using v2 of the WordPress REST API, it looks like the current method of controlling the number of results returned is:
website.com/wp-json/wp/v2/posts/?per_page=100
Replace 100 with the desired count.
If you're using a custom post type, replace posts with the custom post type. Also make sure to set 'show_in_rest' => true when configuring the custom post type.
Add the filter[posts_per_page] parameter to the query to restrict the number of results returned by the API.
http://thisismywebsitewherewordpresslives.com/wp-json/posts?filter[posts_per_page]=2&fiter[category_name]=Some Category Name I want to query&filter[order]=ASC
The above query should return only 2 results. The list of query parameters are present here https://github.com/WP-API/WP-API/blob/master/docs/routes/routes.md#retrieve-posts
As another said : (v2)
http://example.com/wp-json/wp/v2/posts?per_page=10
But If you want to get more next posts : (paged)
http://example.com/wp-json/wp/v2/posts?per_page=10&page=2
Docs : http://v2.wp-api.org/reference/posts/ (Scroll to List Posts)
My recommendation above is no longer correct. Now you'll want to use:
website.com/wp-json/wp/v2/posts/?filter[posts_per_page]=100
Change the number to retrieve more or fewer posts. Change "posts" to your custom post type if necessary and make sure to set 'show_in_rest' => true when registering the custom post type.
Note: While setting the posts_per_page value to -1 worked in earlier beta versions of the plugin (2.0-beta13.1), it does not seem to work in the most recent versions. Now it seems you must define a value in the endpoint.
Currently the API imposes a 99 post limit return. So the max is website.com/wp-json/wp/v2/posts/?&per_page=99, that said it seems like you can modify to allow for additional posts. There's a discussion on that here: https://github.com/WP-API/WP-API/issues/2914
You might change:
add_action( 'rest_YOUR_CPT_params', function($params){
if ( isset( $params ) AND isset( $params[ 'per_page' ] ) ) {
$params[ 'per_page' ][ 'maximum' ] = 500;
}
return $params;
});
And in fetch url add ?per_page=500
Example: https://domain.pl/wp-json/wp/v2/books?per_page=500
The arg in V2 is "per_page" - http://v2.wp-api.org/reference/posts/
I'm surprised no one mentioned using the native filters WordPress has created for situations exactly like this.
I was able to achieve returning a desired amount of posts by default, while still allowing the $_GET['per_page'] param to work like so:
/**
* Default to all posts being returned rather than the default 10 posts per
* page. Also, do not get in the way of the native $_GET['per_page'] setting.
* #param {int} $newDefault The new default amount of posts to return per paginated page
* #var {void}
*/
function setRestApiPostsPerPage($newDefault) {
foreach (get_post_types() as $i => $postType) {
add_filter( "rest_{$postType}_query", function ($args, $request) {
if (! isset($_GET['per_page'])) {
// new default to overwrite the default 10
$args['posts_per_page'] = $newDefault;
}
return $args;
}, 15, 2);
}
}
I did find out you can't set $args['posts_per_page'] = -1; That results in an error being thrown which you can see here.
You can throw any logic within the closure/callback/filter to set the $args['posts_per_page'] however you'd like to.
In reference to Aaron Nusselbaum answer but corrected a few things:
add_filter instead of add_action
filter name must contain additional '_collection', so 'rest_YOUR_CPT_collection_params'
For example:
add_filter( 'rest_comment_collection_params', function($params){
if ( isset( $params ) AND isset( $params[ 'per_page' ] ) ) {
$params[ 'per_page' ][ 'maximum' ] = 500;
}
return $params;
});

Generate HTML web form from XML configuration file with Perl and vice versa

I am in need of assistance with the following problem. There is an application that I co-wrote and currently manage that is written in a combination C and Haskell. The application can be customized and configured via a single XML file. It is a back-end application with no user interface. We have been asked to provide a graphical interface to this application via a web interface. Each configuration option is a form field in the html form like this
configuration1 string1
configuration2 string2
etc
etc
The graphical front end must be a web form that converts the data the user has entered to an XML file that contains the application settings. When the user saves the form, the changes are written to the XML file. When the user opens the form, the configuration from the XML file is displayed in the HTML form fields.
Our team deals with purely back-end stuff and we know nothing of GUIs and the like. The restriction we have is that the front end must be written in Perl and use the LibXML module to conform with company standards. Our team is purely C and Haskell and this is the first request we have ever received for something like that. I would appreciate any help you can provide. If you can include code examples as elaborate as possible it would be a significant help. We know very little Perl but with a clear enough example we can do it. The team that would normally handle this type of stuff is being restructured and we can't wait as we need to get this interface up as quickly as possible.
Thank you.
Don't do this yourself. You don't know Perl or web-apps and the restrictions you mention regarding libxml are probably only one of several. Every tiny configuration and typing mistake will take you hours or days to figure out. You'll end up miserable and stressed, and so will the users.
Someone from your web team could produce a simple form with supporting tests and documentation in a day. You can then extend and bug-fix secure in the knowledge you start from a working app.
If you can't get someone in-house, you cold hire a coder, but do everything you can to get it done in-house first. Don't do this yourself.
To the OP: you did not describe the configuration format properly, an XML fragment would have helped us. As it is you will probably have to modify the solution below to match your format.
I assumed a the following format:
<conf>
<option><name>configuration1</name><value>string1 modified</value></option>
<option><name>configuration2</name><value>string2 re-modded</value></option>
<option><name>configuration3</name><value>string3</value></option>
</conf>
Code that would process this format would be:
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw( -nosticky -utf8 :standard form );
use XML::LibXML;
my $CONF="/web/data/conf.xml"; # or wherever your XML is located
# dispatch table, action => code to process it
my $dispatch= { display => \&display_conf,
edit => \&display_edit_form,
save => \&save_edits,
};
# action is "what to do"
my $action= param( 'action') || 'display';
$dispatch->{$action}->() || exit_error( "wrong action");
exit;
# load the XML and build a table to display it
sub display_conf
{ my $conf= XML::LibXML->load_xml( location => $CONF);
my $content;
foreach my $option ($conf->findnodes( '/conf/option'))
{ $content .= Tr( td( $option->findvalue( './name')),
td( $option->findvalue( './value'))
);
}
$content= table( $content);
# add a link to the edit form
$content .= p( a({ href => url() . '?action=edit' }, 'edit'));
output( $content);
}
# load the XML and build a form that will let you edit it
sub display_edit_form
{ my $conf= XML::LibXML->load_xml( location => $CONF);
my $content;
foreach my $option ($conf->findnodes( '/conf/option'))
{ $content .= Tr( td( $option->findvalue( './name')),
td( input( { type => "text", size => 40,
name => $option->findvalue( 'name'),
value => $option->findvalue( './value')}
)
)
);
}
$content= table( $content);
$content= form( { action => url() },
hidden( { name => 'action', value => 'save', override => 1 }),
$content,
submit( 'Save'),
);
output( $content);
}
# load the XML, go through all options, update the value from the form,
# save the XML, display it value, from the form
sub save_edits
{ my $conf= XML::LibXML->load_xml( location => $CONF);
foreach my $option ($conf->findnodes( '/conf/option'))
{ my $new_value= param( $option->findvalue( './name'));
my( $value_node)= $option->findnodes( './value');
$value_node->removeChildNodes();
$value_node->appendText( $new_value);
}
$conf->toFile( $CONF);
display_conf();
}
# placeholder,
sub exit_error
{ my $message= shift;
print header(), p($message);
}
# output subs, load the template, inject the content and output (with header)
sub output
{ my $content= shift;
print header(), fill_in_string( template(), content => $content );
}
sub fill_in_string
{ my( $template, %param)= #_;
$template=~ s{<<(\w+)>>}{$param{$1}}g;
return $template;
}
sub template
{ return join '', <DATA>; }
# template, very simple
__DATA__
<html>
<head>
<title>Configuration Editor</title>
</head>
<body>
<h1>Configuration Editor</h1>
<h2>Configuration</h2>
<<content>>
</h2>
</body>
</html>
Deployement: put the code somewhere it can be run as CGI, and make sure conf.xml can be read and written by the web server. It's probably better to put it outside of the web tree.
This is in a way prehistorical Perl. CGI is widely considered archaic and there are more modern and fancy options available in Perl. If your configuration is more complex than a key/value list, if you want to have custom help for each field or if you need to use a more complex template to conform to your company's look'n feel, then web Frameworks like Dancer or Mojolicious would be better suited than the simple solution above.
OTOH it works, and I this is still how I write a lot of small tools, that have a few internal users and don't need much in terms of UI.
To the people who suggested that this is too complex to do for people not familiar with Perl, way to go guys! This is not rocket science. It's the kind of code that gets people to start with Perl, why wouldn't we help with writing it? This is in fact a perfect illustration of The Reluctant Perl Programmer.

How to use node_load()?

Hi m a bit confused that how to retrieve node title by using this code
node_load($nid);
$title=$nid->title;
i have done this coding in block and i wants to retrieve from node id for displaying image.that images are normally uploaded at the site by using filezilla and it has same name as the node title.i have tried many forms of node_load(),but i m failure.so please tell me right option for this.
Thanks all.-Pranoti
Here is the reference for node_load
http://api.drupal.org/api/function/node_load
It returns an object which is the node.
$node = node_load($nid); // $nid contains the node id
$title = $node->title;
Please get a good book on Drupal Module development to learn the fundamentals.
Your question is a little confusing. Could you clean it up and explain better what you are trying to accomplish? In all events:
Node load takes either an numeric argument or an array of parameters to query, and returns a single node object. (As already mentioned, here's the API documentation: http://api.drupal.org/api/function/node_load).
Load with a numeric node id:
$nid = 55;
$node = node_load($nid);
$title = $node->title;
Load by querying on title:
$title = 'How to serve man';
$node = node_load(array('title' => $title));
$body = $node->body;
you can also load multiple node load efficiently by using the following code
<?php
$type = "product_type";
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $products):
?>
<?php print $products->nid; ?>
<?php print $products->title; ?>
<?php endforeach; ?>
also you can query any thing in the node load for example we have used type in query but we can also use title as mentioned in the above post by
"David Eads"
NODE LOAD BEST PRACTICES
If you are loading a lot of nodes with node_load(), make sure to use the $reset parameter so that every node isn't kept in the function's static cache (and increasing memory usage):
$nid = 55;
$node = node_load($nid, NULL, TRUE);