# Friday, 28 May 2010
A true REST interface with full support for HTTP Verbs, status codes, and URIs is currently not available on the Salesforce.com platform. However, a simple REST-like interface for getting objects can be developed using Salesforce Sites, Visualforce, and Apex.

This example uses a free Developer Edition with a Site named 'api' that uses only 2 Visualforce pages named 'rest' and 'error'. The rest page accepts a single parameter named 'soql', executes the SOQL query, and returns a JSON formatted response.



The error page is also used to generically handle all 40x and 50x errors.



The body of the error page returns a simple JSON message that the api is unavailable.
<apex:page contenttype="application/x-JavaScript; charset=utf-8" 
showheader="false" standardstylesheets="false" sidebar="false">
{"status": 500, "error": "api currently not available"}
</apex:page>

The rest Visualforce page (full source at bottom of this post) accepts a SOQL parameter and returns JSON results. To get a list of all Leads with their First and Last names, you'd use the SOQL

select Id, FirstName, LastName from Lead
and pass this query to the REST interface in a GET format such as (example here)
http://cubic-compass-developer-edition.na7.force.com/api?soql=select%20Id,%20FirstName,%20LastName%20from%20Lead

Note that the rest page is defined as the default handler for the site named 'api', so it's not required in the URL.
This simple interface supports any flavor of SOQL, including the WHERE and LIMIT keywords, so you can pass queries like

select Id, FirstName, LastName from Lead where LastName='Smith' limit 20
REST interfaces often assume the unique ID of an object is the last portion of the URL request. This can similarly be achieved with a query like (example here)
select Id, FirstName, LastName from Lead where Id='00QA00000019xkpMAA' limit 1

All of these example queries will only return the Id field by default. To fix this, update the Sites Public Access Settings and grant Read access to the Lead object.





The new URL rewriting feature in Summer 10 provides some additional options the necessary means to implementing a RESTful interface with full support for object URIs and linking.

Visualforce Source Code for rest.page
<apex:page controller="RESTController" action="{!processRequest}" 
contentType="application/x-JavaScript; charset=utf-8" showHeader="false" 
standardStylesheets="false" sidebar="false">
{!JSONResult}
</apex:page>
Apex Source Code for RESTController.cls
public with sharing class RESTController {
	public void processRequest(){
		validateRequest();		
    	if( HasError )
    		return;
    	
    	//Add support for other types of verbs here
    	processGetQuery();
    }
    
    static final string ERROR_MISSING_SOQL_PARAM = 'Bad Request. Missing soql parameter';
    static final string ERROR_SOBJECT_MISSING	 = 'Bad Request. Could not parse SObject name from SOQL';
    static final string ERROR_FROM_MISSING		 = 'Bad request. SOQL missing FROM keyword';
    public void validateRequest(){
    	if(Query == null){
    		errorResponse(400, ERROR_MISSING_SOQL_PARAM);
    	}
    	else if(sObjectName == null){
    		//Force a get of object name property.
    		//Detailed error response should already be logged by sObjectName parser
    	}
    }
    
    public boolean HasError = False;
    private void errorResponse(integer errorCode, string errorMessage){
    	JSONResponse.putOpt('status', new JSONObject.value(errorCode));
    	JSONResponse.putOpt('error', new JSONObject.value(errorMessage));
    	HasError = True;
    }
        
    public void processGetQuery(){
    	Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(SObjectName).getDescribe().fields.getMap();
    	List<JSONObject.value> objectValues = new List<JSONObject.value>();
    	List<sObject> resultList = Database.query(Query);
 		
    	for(sObject obj : resultList){
    		JSONObject json = new JSONObject();
    		json.putOpt('id', new JSONObject.value( obj.Id ));
    		for(SObjectField field : fieldMap.values() ){
    			try{
    				string f = field.getDescribe().getName();
    				string v = String.valueOf( obj.get(field) );
    				json.putOpt(f, new JSONObject.value( v ));
    			}
    			catch(Exception ex){
    				//Ignore. Field not included in query
    			}
    		}
			objectValues.add(new JSONObject.value(json));
    	}
    	JSONResponse.putOpt('status', new JSONObject.value(200));
    	JSONResponse.putOpt('records', new JSONObject.value(objectValues));
    }
    
    private string m_query = null;
    public string Query{
    	get{
    		if(m_query == null && ApexPages.currentPage().getParameters().get('soql') != null){
    			m_query = ApexPages.currentPage().getParameters().get('soql');
    		}
    		return m_query;
    	}
    }

	static final string SOQL_FROM_TOKEN = 'from ';    
    private string m_sObject = null;
    public string sObjectName{
    	get{
    		if(m_sObject == null && Query != null){
    			string soql = Query.toLowerCase();
    			
    			integer sObjectStartToken = soql.indexOf(SOQL_FROM_TOKEN);
    			if(sObjectStartToken == -1){
    				errorResponse(400, ERROR_FROM_MISSING);
    				return null;
    			}
    			sObjectStartToken += SOQL_FROM_TOKEN.length(); 
    			
    			integer sObjectEndToken = soql.indexOf(' ', sObjectStartToken);
    			if(sObjectEndToken == -1)
    				sObjectEndToken = soql.length();
    			
    			m_sObject = Query.substring(sObjectStartToken, sObjectEndToken);
    			m_sObject = m_sObject.trim();
    			system.debug('m_sObject = ' + m_sObject);
    		}
    		return m_sObject;
    	}
    }
    
    private JsonObject m_jsonResponse = null;
    public JSONObject JSONResponse{
    	get{
    		if(m_jsonResponse == null)
    			m_jsonResponse = new JSONObject();
    		return m_jsonResponse;
		}
		set{ m_jsonResponse = value;}
	}
    
	public String getJSONResult() {
    	return JSONResponse.valueToString();
	}
	
	public static testMethod void unitTests(){
		RESTController controller = new RESTController();
		controller.processRequest();
		system.assertEquals(True, controller.HasError);
		system.assertEquals(True, controller.JSONResponse.has('status'));
		system.assertEquals(400, controller.JSONResponse.getValue('status').num);
		system.assertEquals(True, controller.JSONResponse.has('error'));
		system.assertEquals(ERROR_MISSING_SOQL_PARAM, controller.JSONResponse.getValue('error').str);
		
		controller = new RESTController();
		ApexPages.currentPage().getParameters().put('soql', 'select Id fro Lead');
		controller.processRequest();
		system.assertEquals(True, controller.HasError);
		system.assertEquals(True, controller.JSONResponse.has('status'));
		system.assertEquals(400, controller.JSONResponse.getValue('status').num);
		system.assertEquals(ERROR_FROM_MISSING, controller.JSONResponse.getValue('error').str);
		
		controller = new RESTController();
		ApexPages.currentPage().getParameters().put('soql', 'select Id from Lead');
		controller.processRequest();
		system.assertEquals(False, controller.HasError);
		system.assertEquals('Lead', controller.sObjectName);
		
		Lead testLead = new Lead(FirstName = 'test', LastName = 'lead', Company='Bedrock', Email='fred@flintstone.com');
        insert testLead;
        
        controller = new RESTController();
		ApexPages.currentPage().getParameters().put('soql', 'select Id from Lead where email=\'fred@flintstone.com\'');
		controller.processRequest();
		system.assertEquals(False, controller.HasError);
		system.assertEquals('Lead', controller.sObjectName);
		system.assertEquals(True, controller.JSONResponse.has('records'));
	}
}
Tuesday, 01 June 2010 11:39:44 (Pacific Daylight Time, UTC-07:00)
Mike: we should compare notes. I've done some similar work to do RESTful querying, creating, updates and deletes. This might be a great thing to turn into a Google Code project - anyone with a Force.com Site could install a package to enable a REST API.
Tom Patros
Tuesday, 01 June 2010 11:42:18 (Pacific Daylight Time, UTC-07:00)
Tom - Definitely count me in as a contributor to an open source REST interface for Salesforce. Lot's of ideas flowing now.
Mike Leach
Monday, 28 June 2010 00:02:08 (Pacific Daylight Time, UTC-07:00)
Very glad to see you in this article
Thursday, 19 August 2010 11:56:44 (Pacific Daylight Time, UTC-07:00)
Mike,

I came across this post while googling for a REST API for Salesforce and I was surprised to see that there was none (at least none I could find).

I work for JackBe and wanted to share how I created a REST (like) API using JackBe's Presto Mashup Server. Here is my blog post related to this - http://www.jackbe.com/enterprise-mashup/blog/simplify-salesforcecom-api-using-presto.
Thursday, 02 December 2010 00:23:52 (Pacific Standard Time, UTC-08:00)
Indonesia's per capita GDP in the next two years among the 20% expected rate of growth. Beginning in 2009, Indonesia has been maintained expressive second Asian stock markets. Some analysts suggested that the BRIC countries will probably increase in the near future a member.


Wednesday, 23 February 2011 05:54:10 (Pacific Standard Time, UTC-08:00)
Excellent! Thanks for doing this…it’s really nice to know that I’m not alone on a lot of these things.
Wednesday, 16 March 2011 08:48:59 (Pacific Standard Time, UTC-08:00)
Maybe I am blind and missed it but where is the JsonObject class. Are you using this package, http://developer.force.com/codeshare/apex/ProjectPage?id=a0630000002ahp4AAA ?
Wednesday, 16 March 2011 10:16:26 (Pacific Standard Time, UTC-08:00)
Hey Jason - Yep. JSONObject is from the code share at http://code.google.com/p/apex-library/source/browse/trunk/JSONObject/src/classes/JSONObject.cls
Mike Leach
Tuesday, 22 March 2011 18:01:54 (Pacific Standard Time, UTC-08:00)
Sony Vaio VGN FE Series Battery police opened Sony Vaio VGN FJ Series Battery fire on a crowd of protesters, as riot police at the scene did Sony Vaio VGN FS Series Battery not carry weapons. He accused Sony Vaio VGN FT Series Battery anti-government protests
Thursday, 31 March 2011 02:26:13 (Pacific Standard Time, UTC-08:00)
<P> Horizontal version of the first actions of domestic quality 3D gaming, "Warriors OL" is about to enter the official closed beta stage, Jiuyou Wang Chairman of the Board and Chief Executive Wang Zijie, said in an interview: "Warriors OL" R & D process is quite tortuous, lasted about four years, insist on quality first, do not be satisfied by no means easy to open R & D testing philosophy, the pursuit of breakthroughs and innovation, planning and overcome many technical difficulties. In addition to strive to lay a solid foundation in the content, innovation, the design of which is equipped with dual 3D Action online games to lead the market development potential. Therefore, we "Warriors OL" confidence in market performance after the listing! </P> "Warriors OL" "3D stereo visual effects," the leading idea! <P> Wang Zijie continue to explore in depth: "The Warriors OL" double 3D design mainly in 3D stereo visual effects and 3D game engine based on the action production. "Warriors OL" will be launched first in the industry to achieve "3D stereo visual effects," the scene and the copy of the payment to the players a lot of 3D stereoscopic glasses, a positive experience to meet the players in online games in 3D stereo visual effects needs. Action online games, because the response time requirements, wow is most similar products on the market with 2D design, and "Warriors OL" R & D since the beginning of four years ago, decided to use all of the Gamebryo 3D engine, and in the development process to overcome the increase response time of the technical difficulties. R & D personnel in ensuring the smooth flow of texture and the fight against influenza and other basic wow gold premise of using 3D design, which not only enhance the picture effect, enriching the action effects, and equipment to achieve the 3D effect, but also makes the game action and special effects designed to enhance production efficiency than the 2D at least a few times, make the game in the content richness, updated version of the speed and tracking ability to lead on the theme of cultural hot spots is expected to greatly exceed the market of similar products. We look forward to, "Warriors OL" double the performance of 3D design to final validation foresight, establish a cross-board 3D action online games new milestone. </P><P><BR> Depth of field to create the gorgeous 3D world engine </P><P> Speaking of survival games, the Wang Zijie said: We all basically agree that the so-called content industry, "eighty-two law", and I think that the integration of content and technology from the gaming industry can even be said to be a "law of the September "Leading the field. Undoubtedly have a decisive role in product quality, but how rift plat to reflect the quality first is a benevolent see benevolence and the wise see wisdom of the problem. "Warriors OL" R & D process can be fully reflects the next generation of online games is actively promoting the strategy Jiuyou Wang understanding for the quality first, our goal setting and development of the whole process has three basic requirements: </P><P> The first is impatient haste ring, do not be satisfied by no means lightly on the line, basic research and development in the whole period of four years, has been fighting a lot of similar cross-board market, but "Warriors OL" team still Zuohuaibuluan , toward the established goals quietly forging ahead. </P><P> Secondly, the "Warriors OL" requires solid foundation in technology, content, innovation, research and development process requires close the entire audience and repeated scrutiny. After several rounds of internal and external closure, after testing and user research, online technology as the basis for the action action to combat flu and Shuangkuaigan aspects "Warriors OL" a qualitative improvement, I believe you can officially measured in the upcoming version of the full experience and feelings. In the content design, the "Warriors OL" also reflects a positive and innovative ideas, for example, into a comprehensive pet system as the basic game play is one point, riding a pet, flying pet, pet care, pet capture, pets and other domestic players are familiar with the fighting and preferences of play throughout the entire course of the game, I believe can greatly enhance the process of the game fun and entertainment content. In addition, the "Warriors OL" interactive features of similar products are also relatively larger increase, the import of the team, gang warfare, the interaction level of play MMORPG. </P><P><BR> Ride with your pet all the way to grow </P><P><BR> Tips for flying a private action online games pet </P><P> Finally, the vitality of online content in its continuous improvement, development and updates. "Warriors OL" requires not only a version of R & D team to achieve speed and efficiency in 3D design embodies the essence of advantages, and must be followed by social hot spots, with the times. Updated version of its follow-up piece of content and data into an active social and cultural hot topics and enhance the cultural content of each version, to achieve the introduction of products can not be realized by the substitution of a sense of local culture. At the same time, we will actively implement the operational aspects of the "three resort" strategy, in the opening game in one fell swoop within six months after the test launch of three major heavyweight piece of information or an updated version of the game to enhance the user attention and confidence. </P><P> I believe keeping a low profile Jiuyou Wang four years, carefully planned cross-plate honed 3D action online games will shape a national independent research and development of a horizontal plate new milestone in action online games, I hope the majority of players involved in the cross-board experience this 3D action online games, Let us meet in closed beta Warriors OL! </P><BR>
Thursday, 31 March 2011 02:55:07 (Pacific Standard Time, UTC-08:00)
As a pation and crazy players. I often buy cheap wow gold and dofus kamas. strongly recommend buy dofus kamas, click here to buy rift plat.
Saturday, 09 April 2011 04:45:42 (Pacific Daylight Time, UTC-07:00)
Thanks for sharing! it is good to encourage people to comment, not just reading. The only reason I writing blog rather than diary is because of the feedback.
Tuesday, 12 April 2011 18:52:13 (Pacific Daylight Time, UTC-07:00)
Hey Jason - Yep. JSONObject is from the code share at http://code.google.com/p/apex-library/source/browse/trunk/JSONObject/src/classes/JSONObject.cls
Christian Loubotuin Leather Butterfly Bootie
Christian Louboutin Suede Butterfly Bootie
Christian Louboutin cognac suede Lady Derby 120 lace up peep toe booties
Sunday, 17 April 2011 23:00:22 (Pacific Daylight Time, UTC-07:00)
wow, this is a lto of comments.
Wednesday, 04 May 2011 02:39:53 (Pacific Daylight Time, UTC-07:00)
Although cheap jordans free shipping the NBA cheap jordans for sale Playoffs are air jordan vi in full swing air jordan 13 retro and Lebron James air jordan 11 retro himself will cheap air jordan 9 retro most likely cheap nike air max be keeping Cheap Jordans to the Playoff version Cheap Air Jordans of his Nike Air Max Lebron 8, that Air Jordans for sale does not mean Authentic Air Jordans other alternatives Authentic Jordans can’t be gathering authentic air jordans for sale hype as authentic jordans sale well. One such cheap authentic jordans Nike Basketball cheap authentic jordans sale design that Jordan XI proves this jordan flight 9 true is jordan flight 45 the “Sprite” colorway jordan six rings of the Nike Air Max Lebron air jordan iii 8 V2 in a low-top cut. After air jordan dub zero seeing what happened Air Jordan Retro 1 to Kobe Bryan’t foot in round air jordan 13 1 of the NBA Playoffs, may air jordan silver anniversary you’ll be less air jordan vi quick to ball in low-top shoes, but the ones pictured nike jordan shoes online sale here would look good off authentic retro jordan on the court just as it would on. So enjoy the following batch of more images of this interesting colorway to see if you’ll think of pursuing.

Wednesday, 04 May 2011 02:40:33 (Pacific Daylight Time, UTC-07:00)
It’Cheap Jordan Shoes s been quite Cheap Jordan Sneakers some time since Jordan Sneakers Sale we’ve taken Cheap Jordan Shoes sale a look at Jordan Sneakers the skater boy-friendly Air Jordan cheap Jordan Sneaker Sale I Phat low. We Jordan Sneaker Sale saw it back Nike Air Jordan 2010 in February when two Jordan Dub Zero colorways were air jordan dub zero introduced, but Air Jordan Silver Anniversary now outdoor jordan 1 flight skating season is actually Jordan Flight 9 upon us and Nike Air Jordan 16.5 they might Air Jordan 10 retro serve more retro air jordan 11 of a purpose. Pictured air jordan 12 retro here is a Air Jordan Retro 1 white/black-deep Nike Air Jordan Retro 1 royal Air Jordan Air Jordan 1 I Phat low that should Air Jordan Retro 11 appeal to jordan xi all you lamenting Air Jordan 14 Magic fans jordan retro 6 (and perhaps also jordan flight 45 soon to air jordan retro 6 be Mavericks fans?). Let us know how you feel about the colorway; but, also, about the design itself since it’s been in sort of hiding.
Wednesday, 11 May 2011 19:52:15 (Pacific Daylight Time, UTC-07:00)
Air Jordans run big
Cool kids
Air Basketball Shoes Sale
Jordan Basketball Shoes On Sale
Nike air foamposite pro silver black cheap
authentic foamposite
Kids shoes
Nike Air Force Ones
Men Air Force One Shoes
awesome air jordans
black metallic gold and black hyperize
Air jordan Kids
New Release Air Force One Shoes
Cheap Air Force One On Sale
cheapest nike zoom cleets
discounted nike zppmoncore 2
Nike Air Jordans
Custom Nike Air Force One Sale
mens phat jordans
nano grey retro ink flint summit white
All Air Jordan Sneakers
Nike Air Max Shoes For Mens
nike sfb black
omcore Black Pine/Urban Haze-Emerald
Cheap Jordans For Sale
Nike Running Shoes
white spice-light retro-black
www.authentic jordan.com
Nike Basketball Shoes
Nike Shox For Cheap
Air Max 2011 Sale
retro jordans
CHEAP OUTDOOR AIR JORDANS
Mens Nike Basketball Shoes
Nike Training Shoes
Nike SB Shoes
kicks is fly T-shirt
nike jordan suns colors
Nike Air Jordan Fusions
Training Shoes Mens White Black
nike zoom vapor carbon fly td men's
cheap nike fomposie pearl
Saturday, 14 May 2011 20:35:23 (Pacific Daylight Time, UTC-07:00)
Soccer is my favorite,so is David Beckham
Tuesday, 24 May 2011 22:30:39 (Pacific Daylight Time, UTC-07:00)
Wedding Dress
Wedding Dresses
Wedding Dresses
Bridesmaid Dresses
Prom Dresses
Evening Dresses
Mother Of The Bride Dresses
Flower Girl Dresses
Vera Wang Wedding Dresses
Wedding Dresses Vera Wang

Brian Atwood
Atwood Brian
Brian Atwood Shoes
Atwood Pumps
Brian Atwood Pumps

Air Max 90
Nike Rift
Nike Air Max
Nike Air Max 90
Nike Shox
Nike Air Max 95
Air Max

Mont Blanc Pens
MontBlanc Pens
Fountain Pen
Ball Pens

Wholesale digital thermometer
Digital Thermometer
Infrared Thermometer
Ear Thermometer
Blood Pressure Monitor
Blood Pressure Monitors
Alcohol Tester

Tory Burch
Tory Burch Shoes
Tory Burch Flats
Tory Burch Handbags
Tory Burch boots
Tory Burch Flip Flops

Air Max 90
Nike Air Max
Nike Air Max 95
Nike Air Max 90

Air Max 90
Nike Rift
Nike Air Max
Nike Air Max 90
Nike Shox
Nike Air Max 95
Air Max

ED Hardy
ED Hardy Clothing
Christian Audigier

Chanel Handbags
Coach Handbags
Louis Vuitton Handbags

Air Max 90 pas cher
Nike pas cher
Nike Shox Pas cher

Nike Air Max
Air Max 90
Air Max 90 pas cher
Nike Shox

Nike Shox Pas cher
Air Max pas cher
Nike pas cher
basket nike pas cher
Air Max 90 pas cher

iphone case
iphone cover
iphone 3GS case
iphone 4 case
ipad case

iphone 4 case
iphone 4 cover
iphone 4 cases

lingerie
sexy lingerie
sexy sexy lingerie
sexy underwear

abercrombie fitch
fitch abercrombie
abercrombie and fitch
abercrombie & fitch

Air Max 90
Nike Shox
Nike Air Max 90
Nike rift

thomas sabo
sabo thomas
thomas sabo jewellery
sabo charms
thomas sabo charms

Links of London
silver jewellery
Links of London Bracelets
Links of London Charms

ysl shoes
jimmy choo shoe
christian louboutin shoe
christian louboutin pumps
jimmy choo boots

Tiffany Jewellery
tiffany uk
tiffany & co
tiffany and co
Tiffany Jewelery
Comments are closed.