I watch for questions at StackOverflow with the ‘salesforce’ tag – this morning, I noticed one asking about how to retrieve a Visualforce page from server side code for the purpose of screen scraping it to extract data. There were a couple of good answers on how to achieve this, but the better answer is “Just don’t do it!” – there’s really no need. Here’s the answer I gave at StackOverflow:
Rendering the data into a Visualforce page, then screenscraping it seems a bit brittle, not to mention inefficient – there is a better way…
Define an Apex REST web service, then you can easily invoke that web service from your server side code, and still render it in Visualforce if you need to – you can call an Apex REST method like any other Apex method.
Here’s a sample REST web service. I’m just returning a
Map<String,String> here, but you can return any primitive type, any sObject or a List or Map of primitives or sObjects (as long as the Map has String keys) – see the Apex REST Web Services docs
Here’s some PHP that calls it (I’ll assume you have an access token (aka session ID) and instance URL):
And here’s a Visualforce page, if you want to show the same data
The page controller:
If you’re a StackOverflow user (and if you’re not, you should be!), please go vote my answer up so that best practice wins out!