Start building your own REST API in Salesforce using Apex

What is the need ? 

Salesforce platform is amazing and its lets your create your own lightweight  REST API using Apex. You can use this REST API to access data, by authenticating the caller/consumer of API using standard oAuth and return data format support JSON/XML, purely depends how you want return back the data

I personally call this concept as custom REST web services to make it sound simpler, but how different is the REST API than a web service ? Well, the edge of using building REST API over web services is that, API enjoys pleasant features of REST architecture which is object mapping which mean that REST reads the data-tables (data model) for you and supports object mapping, that is actually the (process of transforming data in one form and transforming into other), so you once properly authenticated, you can access data through URL.

REST in apex supports basic CRUD (create, read, update and delete) operations, to create rest API of your own you need to define the set of operation that is supported over http. After writing REST API we can enjoy the full support of REST behavior.

To declare the rest API, first step is define the endpoints, you can define a class as endpoint, which in other words mean this class is exposed as a web service and can be accessed through a url for the authenticated call.

Lets create a connected application on the first step to make an authentication for requester. Go to Setup and create a new connected application, as shown in picture, for now lets give full access to requester

Connected App

Apex Endpoints :

Lets define the Apex endpoint, basically the address which we call from the url, for demo the Apex Endpoint here is Oyecode, so lets create a class with the name OyeCodeController and that perform two operations

1. Create a contacts
2. Pull back the contact, if provided with Id

Here is the Apex Endpoint

Lets create special class that handle response you receive from API called ResponseHandler, this allow use to drive the information which we want to return back once API is requested.

I am defining ResponseClass with five attributes

Now clearly our response class will look like this

Once we have structure ready for API response, lets start carving class that use response.

In this example, I am performing the two basic operation with API  '@HttpPost and @HttpGet' so I am creating two separate methods for handling operation here

Below is the @HttpPost Method to create new contact

Here is @HttpGet method to retrieve contact by Id

So clearly, I wrote custom methods on top of this retrieve contact using SOQL and inserting a new records, here is full blown view of our freshly built API

Accessing API

Lets start using the API we just built, there are multiple way you can access API but easier way is using curl (which some folks may not like it) but I have written a template code here that can be reused to access Salesforce API

Testing  : @HttpGet

Curl Command to generate access token through connected app using command line tool, to generate your curl command check this post 

On sending the request using curl or hurl you see this response on matching id on other favorite rest client

This is how simply you can create a custom API in Salesforce and I recommend reading these post as well for more details

1. Apex Rest on by Peter Knolle
2. Building Rest API by Jeff Douglas

Google Polymer | Create your first custom html tag in minutes

I have been writing about polymer since two weeks by now, I gradually started developing my own components and decided to share my experience working with polymer. I would like to share how to make a simple but working custom polymer element and consume it. Before moving further, if you want to see what Salesforce had built on already on Polymer than read my post here and here 

Why Custom Elements ? 

Custom elements lets the author of code design their own custom tags like for example if you want to embed youtube or any other side video on a page you can simply do
<video-frame url=''></video-frame>
and one line code will result in this

How to build this ? 

To get started lets built a simple application that use custom tag we will built here, but to run this you need bunch of dependencies like polymer.html and polymer.js files. To download this, we will use bower package manager.

I prefer mac for most of my development, these commands are supported on apple.

Install bower as package manager that pull and saves all the related dependencies for you in one place.

Create  new directory/folder on your machine and through command line/ shell navigate to directory. Type in the following commands (like I am doing after navigating inside Oyecode_Polymer) directory
$ bower install  
$ bower install -save polymer 
You can install polymer in one line using bower with just two commands above. Having run this command, now create a new html  file called myelement.html. Copy paste this content in your new html file.

This is how my directory look like 

Lets create our first custom defined html tag or polymer element in other words.

<!-- Define element -->
<polymer-element name="video-frame" attributes="url" noscript>
  <iframe width="560" height="315" src={{url}} frameborder="0" allowfullscreen></iframe>

Remember this element uses javascript, if you do not want your element to start a script you can added NoScript tag like this

<polymer-element name="my-element" attributes="counter" noscript>

Let us use this custom tag by adding to html page. On render, this tag will result in html button which on click will increase the counter by +1 based on what attribute value you provided to the element. Remember, this example is officially demonstrated by Google.

<!-- Use element : Adding four videos-->
<!DOCTYPE html>
<script src="bower_components/platform/platform.js"></script>
<link rel="import"  href="bower_components/polymer/polymer.html">
<link rel="import"  href="bower_components/video-component/videoframe.html></head>
<video-frame url="//"></video-frame>
<video-frame url="//"></video-frame>
<video-frame url="//"></video-frame>
<video-frame url="//"></video-frame>

How to run the project
  • using cd command to go your directory like  $ cd ~/Desktop/Oyecode_polymer 
  • type in python -m SimpleHTTPServer to start server

Python 2.x:
python -m SimpleHTTPServer 
Python 3.x:
python -m http.server 
Test out the web server by loading the finished version of the project. For example:
Here is the output 

Press increment button to increment the counter, and you see once you have element ready, just in one line of code, you create a button, with counter displaying number and changing on click. I wrote couple of more element and have been explaining more in upcoming post about developing elements and event handling to achieve more awesomeness

Fork my repo here on harshit branch and jump start  here

Try any Salesforce API quickly with Curl command templates

Working with tons of application here at Salesforce, I got a chance work with wide gamut of internal and externally exposed API's. Over the period of time, I developed a curl template, that I used in command prompt or Mac terminal to consume api in no time. I treat this template as my key resource to connect to Salesforce api's in matter of minutes and then move on writing code in more proper fashion for designing the client.

Create a connected Application in Salesforce 

To understand the templates better, go your salesforce org, login and create a connected application in 
   'Setup -> Apps -> Connected Apps' 
Grab the Consumer Key and Consumer Secret after creating application, save them, before we move on. Now we can use these credentials to authenticate the api-user and get API Token, once we have API token the last step would be to access the API to pull data we want.

Download curl here for (windows and mac)

(1) Curl API Authentication Template - for Salesforce API Authentication 

Copy this code snippet shown below in sublime or your favorite text editor and replace with your login credentials (consumer key, consumer secret, username, password) and then paste the template on command prompt in mac terminal to receive the API token in the response from REST API. I used Iterm mac terminal in my machine. Once your post the request, then see if, the response you get after posting, matches with the one shown in this snippet here.

I'll use this authentication and data-access curl template for two of the popular salesforce application programming interfaces, Salesforce Analytics API and Salesforce Tooling API

How to get started with Salesforce Analytics API ?

Awesome, so we have the access to API now, lets us kickstart with Salesforce Analytics API and pull a report details, salesforce analytics api can be used to bring all analytics of transaction you made on top of salesforce, lets say you want to represent data by pulling from a Salesforce report in form of Chart/Dashboard based on javascript, you can use Analytics API to pull data.

Jump in here on documents for Salesforce Analytics API (using REST) and  have a look how you can pull the report metadata  by providing the report Id. I created a matrix report on Opportunity and I'll use the report ID to pull metadata of this report. Remember the response would be in the JSON format.

Reading docs, it clearly says you can pull data for this matrix report by requesting Salesforce analytics
Api in the url format shown here

This GET request, /services/data/v29.0/analytics/reports/00OD0000001ZbP7MAK/describe, to the Describe resource returns metadata for a matrix report. This includes a bucket field, groupings, summaries, and a custom summary formula.

(2) Curl Data Access Template - for accessing data from Analytics API

Replace API Token with your token and run this command prompt again like I did here in the picture.

Bingo - you get the JSON body response, you are ready to rock now

Copy paste and go to JSON beautifier to beautify the response from this junk this format to beautiful looking JSON response like here

Brilliant, we did it !! Now let us create new connected application to pull data from Salesforce Tooling API. Now, I am going to pull the 'list of all sobjects' but with tooling api.

How to get started with Salesforce Tooling API ?

Tooling API can be used to retrieve meta data information about salesforce elements, like finding the code coverage of the class, list of objects and all meta-data of salesforce structures. You can use this api to modify existing salesforce tools : Read more about Tooling API here 

Lest get the list of SObjects in my current Salesforce org. Now, to get the list of sobjects in your org, you need to pass this params in the url
Lists the available Tooling API objects and their metadata.

Brilliant, using the 'Template (1)' as shown above, I replaced my credentials again I replaced both consumer key and client secret' by creating a brand new connected application from scratch

Lets Authenticate using Login Template

Now once you get API token, lets query Tooling API by through this url
Result is exciting

Sooner, I'll share the sample application I built on top of Salesforce that uses salesforce and remote objects to pull data plugging into API you needed. I hope this template will helpful for you in playing and spreading Salesforce API love all over world and among the community.

Sharing is Caring 

How to use Google Polymer with Salesforce | Design Custom UI for Salesforce 1 Mobile Applications

This is the library, I have been playing around since couple of days, I am amazed to see the potential of designs you can make with bare minimum code. Salesforce mobile pack for polymer is designed by mobile sdk team, which is now an open source project. The project solely sits on top of Google Polymer platform. Basically, these are collection of web-components that links the data to Salesforce. On the back-end, the components connects to Salesforce using Forcetk and other JavaScript libraries with collection of style-sheet that follow design guideline provided by Salesforce, these are available as components.

What is Google Polymer and Web Components?

In my last post here, I have discussed the architecture and what define a web component and how they work with Google Polymer.

What does this Library Do ? 

This library provides fundamental building blocks to create application on HTML5 that runs on top of mobile platform. I would like to give special thanks to mobile team lead here +Akhilesh Gupta  for spending great time about insight and potential of the library. Again, this library is under heavy development and feel free to raise issue/question either github or Salesforce Mobile SDK team.

Mobile UI elements are web components made on top Google Polymer Framework and allows you custom design elements. Polymer platform provide designer (studio like) UI for components, this designer lets you drag and drop components and link to your salesforce organization to pull data from your salesforce organization.

Login : One click to connect with Salesforce and authorize to use your org.


Drag and Drop UI : Smoothly drag and drop UI components from the side-panel.


You can drag-drop elements in the designer app (similar to design studio) which allows you to freely drag-drop the UI elements and plug in with data source to populate.
Primarily the library is collection of two sets of elements, the data-elements and visual-element (UI-elements),  the data-elements are data binders, that lets developers, link to data source and comes with attributes to filter and manipulate data, while on the other hand, UI components are visible components which you can see while dropping them on designer studio and again comes with attributes related to design (like color, size and more)

Data Elements - Attach data elements, the data elements are the data binders that bind the object with view, these are polymer components to be used for linking data source, you can attach/bind/link any custom or standard object of Salesforce with them.


List View - One data is attached you create the list view, you can change the query and queryType to SOQL, SOSL depending on type of query you want to make. The list view gives details of records that match criteria, just drag the header and details view provide the details of record


Detail View - For each record, you can pull header and related list.


Toggle for Auto-Generated Code : Just with one click, you can toggle between designer/code and interestingly you see the total line of code reduced to significant level, which is the power encapsulation that polymer leverages by importing HTML and lots of JavaScript from back-end.


Works with iPhone and iPad : Tested on both iPad and iPhone


How do I jump start ?

You need to get some basic tools to get started
  • Git Client ( I also prefer Iterm or standard mac terminal)
  • Node.js 
Open your terminal then install grunt

Go to simple.html in the git repo (directory) and replace the session Id and instance url as shown here


Make sure your Node.js proxy server is running, in-case your come across any other issue, please  feel free to post comment or else add issue to this GitHub Repository

+Akhilesh Gupta  have just added a proxy on Node.js to run the application locally which is required to avoid Cross Domain Reference error and another proxy has been added for Heroku platform.

Tip *  - Login to your salesforce instance and grab the instance session Id and instance url, you can run anonymous apex to get session ID running anonymous apex in developer console.

Try your hands on designer tool here . In my next post, you will find some of the components I used to demo the application to another level where I am building an application that link to custom object and present data in newer fashion.

Check out this video of +sfhtml5 conference happened next door, presented by +Eugene Oksman  and +Akhilesh Gupta

Getting Started with Google Polymer - Part 1

This post is divided in two parts, first part explains the architecture of Polymer and developing first working application using Google Polymer, while second part would be on using UI elements to create amazing salesforce apps on top of Polymer.

Click to play with this framed app, designed on Google Polymer, this app is now officially published as tutorial by Google :

                                            Courtesy - @PolymerProject 

What is a Web Component Architecture and why we need Polymer ?

To understand the polymer fairly well, lets understand the architecture behind. Google introduced Polymer to simplify web-development using collection of units called Web-components. Ideally, if you plugin these components to your web application, you can speed your application development to a significant level.

Now as we know, building a modern day web application require lot of resource ranging from javascript framework, design frameworks and tons of other web tools. Clearly, the complexity of these resources increases, as the application scale up over the period of time, which later becomes   harder to maintain

Google aimed to solve this problem,  by bridging the gap between rich functionalities of applications  and application resources, without a need of extra libraries through web-components. Google acclaim that, web-component driven development is likely the future of web.

What is a web component ?

In the last W3C release, definition of a web component is expained, and basically a web-component comprise of five specifications (Custom ElementsTemplatesShadow DOM and HTML imports

Custom Elements : the custom elements allow you create your own HTML tags like this : say I have defined custom tag that show Google login form on any page.
<google_login appid='xyz'></google-login>
Shadow Dom - allows you create encapsulate structure inside a DOM element
Html Imports - packages custom elements and a package may include HTML, CSS and JavaScript
Template - binds the data with JavaScript elements and extends functionality of traditional template

Adding these custom tags to any HTML page, can create login form for Google, using web component, in one line of code

Understanding Polymer.js and Platform.js

Polymer is basically divided into four parts :
  1. Native - Features available in currently all browsers 
  2. Foundation - Polyfills that implements all features (combining web-components (Custom-Elements, Templates, Shadow-DOM, HTML-Import) adds support in browsers with features that are not natively supported.
  3. Core  (Platform.js) - required part, necessary to perform capabilities provided by native and foundation layers
  4. Elements - building blocks that you use to create application
Check this image for clear explanation - read more about Polymer Architecture here 

Credit : Google Polymer Project

Let us built first Polymer application, but I would like to mention that, before I released this post, Polymer documentation page, do not have well document application or same code, but now they have couple of  application with step by step tutorial is available for free and is live.
I recommend going to their tutorial page, to built your first application, as elaborated on Google Polymer Project page.

Since, I have developed the application already, following the instructions in the tutorial ,  I am sharing my Github repository,  just fork my code to see the application working right away.

Download or Clone Repository from

Please follow these steps to run the code
  •  Fork the code to your local machine from Github 
  • Go to Shell on Mac and Type  -  python -m SimpleHTTPServer
  • Open the browser and type : http://localhost:8000
In my next post, I would be explaining how to jump start polymer with Salesforce, stay tuned for next update, should be out pretty soon

Check out this amazing video by favorite developer advocate from Google  +Eric Bidelman where he explains how to use Google Docs to populate google map with bare minimum code and get more components here at

Understanding Asynchronous function and Event Loop in Node.js

I built some basic notes to a kick-start on Node.js and which turns out to be very interesting platform and allow you to have full server-side control through java script. I have developed some notes over the period of time and as I discussed here  a blog post about getting started with Node.js, I would like to add some more content moving forward but this time I am focused here to demonstrate some nature of Node.js and the patterns it leverage

Pic Credit :

What is Node.js ? 

Node.js is a server-side technology that's based on Google's V8 JavaScript engine. It's a highly scalable system that uses asynchronous event-driven I/O (input/output), rather than threads or separate processes.

It's ideal for web applications that are frequently accessed, but computationally simple. If you're using a traditional web server, such as Apache, each time a web resource is requested, Apache creates a separate thread or invokes a new process in order to process the request.

Once you install Node.js in your machine here are some basic commands and quick application that you can built in no-time that will help you building application over Node.js

Running Node

Once you install, Node.js package in your machine, go to your CLI (command line interface) or terminal and I strongly recommend to download the third-party terminal called ITerm in macintosh.
Type in    - $ node
This will invoke CLI, which will wait for you to input to an expression
>console.log('Welcome to Node.js'); Welcome to Node.js
Alternatively, you can run Node.js from a simple javascript file, like you create an javascript file with this content ' console.log ('Running Node from file'); .  If you name the file as application.js then you can invoke the file as
> node application.js    --To quit CLI , type in CTRL+C (on your mac machine)

Understanding Node.js functionality through a working application

You can create your javascript file as well, and here I created a file called kissmyapp.js that greets the user whoever access this file.
To run this application save this application as kissmyapp.js and to run this application use
| $ node kissmyapp.js
| $ Server running at 8080

Asynchronous function and the Node Event Loops 

Likewise in Apache, there are two ways to handle the incoming requests,
  • First approach would be (prefork or Multi Processing Model - called MPM) this approach assign each request to separate process until the request is satisfied, the benefit of this approach would be that the application need not have to be thread safe while disadvantage is each process is memory intensive and which clear do not scale so well
  • Second approach is (worker MPM) which spawns thread for each request, so each new incoming request is handled via a new thread and clearly is more memory inefficient but the application have to be thread-safe, PHP on the other hand is not thread safe
Regardless of all, both the types respond to request in parallel, so clearly with fifty people request a server at same time, the web-server handles all request simultaneously 

How does the Node works ?

When you start a node application, it is created on single thread of execution, so clearly it sits there and wait for the first request to come. When it gets a request , then no other request is processed unless first process is finished. Now this many sound very in-efficient, yes but except for one-thing.

Node operates asynchronously, via an event and callback functions the events polls for each events and invoke event handlers for each event so in Node the callback function is event handler

nodejs for dotnet
Picture Credit :

Node processes the request, but doesn't wait around until the request receives a response. Instead, it attaches a callback function to the request. When whatever has been requested is ready (or finished), an event is emitted to that effect, triggering the associated callback function to do something with either the results of the requested action, or the resources requested.

If five people access an application at the exact same time, and the application needs to access a resource from a file, Node attaches a callback function to a response event for each request. As the resource becomes available for each, in turn, the callback function is called, and each person's request is satisfied. In the meantime, the Node application can be processing other requests, either for the same people, or different people.

Node application that read file asynchronously 

What happened here ?

When the connection is established, a listening event is emitted, which then invokes the callback function—outputting a message to the console. Accessing a file is a time consuming operation, relatively speaking, and a single threaded application accessed by multiple clients that blocked on file access would soon bog down and be unusable.

Instead, the file is opened and the contents read asynchronously. Only when the contents have been read into the data buffer—or an error occurs during the process—is the callback function passed to the readFile method called. It's passed the error, if any, and the data if no error occurs.

In the callback function, the error is checked, and if there is no error, the data is then written out to the response back to the client. 
Most people who have developed with JavaScript have done so in client applications, meant to be run by one person at a time in a browser. Using JavaScript in the server may seem odd. Creating a JavaScript application accessed by multiple people at the same time may seem even odder. 

More on Node 

Node is very efficient in handling multiple request from browser, in my next post i'll also be writing an application that creates a client and server and clients sends multiple request to server, like when we request a blog application to show a post , in the meantime time we request to show favicon file, the Node handles this fairly smoothly and then later part would be building some cools application using Express.js which I have been testing in a while

Building SOQL Query Tool with Node.Js - Part II

If you have read my last post on ' Getting started with Node.Js ' then its the time to move on to next post on building cool application on Node.js by integrating to platform. My application is inspired and supported by code-base shared by +Christophe Coenraets (Developer Evangelist here at +Salesforce )where he posted a neat article on building API explorer on Node.

I forked the idea, revamped my logic and complied to create a SOQL Tool on Node.js which turn out to be couple of hours hacking

Lets +Keep Calm and Carry On Hacking.

Download my repo at - with Node.js to get started 

Create a connected application by going to setup->app -> new connected app. Name you application and keep call back url as http://localhost:3000/oauthcallback.html

Since we will be hosting the application on localhost:3000, on success we return to oauthcallback.html page which stays in the directory provided in the github repository.

Once you create the application - you receive the client ID auto generated which you need to copy on the app.js file as shown here

After successfully creating the application, you see the client_Id add the client Id to app.js file here

Follow the instruction shown the video to run the application successfully on your machine.

Node.Js with Salesforce | Getting Started with Node.js - Part 1

Node.Js with Salesforce | Integrating Node.js with Platform

Quite a few people asked me this question, do I need to learn Node.js as Salesforce developer and my answer to them is yes and no. This is actually purely relative question and clearly depends on type of implementation you do with your application . I had spend quite some good time meeting with +Sandeep Bhanot  at Salesforce HQ discussing these topic.

What are the Prospects ? 

With an understanding of Node.js, you will be able to develop real-time, fast, scalable, data-driven web applications, and you will have the requisite knowledge to quickly adapt to any of the emerging, cutting-edge JavaScript frameworks such as Derby.js and Meteor.js.

It is worth noting that unlike just a couple of years ago when you needed to know a true server-side language (such as PHP, Rails, Java, Python, or Perl) to develop scalable, dynamic, database-driven web applications, today you can do as much and more with JavaScript alone.

Lets see in more details , what is Node.Js and how I am goona use it. You may find, lots of resources for learning Node.js but I got my most answers resolved over here  at CodeSchool

I always prefer video over text to get started and once in, documentation reading and understanding is smoother, if you are same type then check out these two cool videos to jump in

What is Node. Js by CodeSchool hosted at my account


Node Tutorial Series by Pedro

My Node.Js - First Application 

I made a sample Node.js application that you can download on your machine. I made a demo video, see the video and follow the instruction to run this application. This video explain, how to install require packages and run the application.

Also, later half of this post will be more focused on connecting the application with Node.js and querying Salesforce. So stay tuned for second part of the post, which is in process

Meantime, try this application, this application let you type your favorite color in the text box and changes the background color the background as you type.

Apex Messages in Salesforce | Show Messages in an easy fashion

Apex Messages in Salesforce are used in displaying messages in standard visualforce pages, unless you are not using the cool frameworks like BootStrap or FlatUI, where you show error messages in a neat fashion.

Before we move on, I would like you go through Apex:Severity messages to see what type of severity can be shown on pages and how are they displayed on pages.

I designed a simple code snippet that handles all sort of apex messages on visualforce pages at one place for you, you can re-use this code at any point in any custom class and show messages in convenient way.

Ideally this is how you show error messages using Apex 

Now I designed a PageHelper class that handles many things but include method that shows the message in modular way, so all you care is calling method with name and pass on message to display on page.

You can call these method by simply calling
PageUtlity.showError('No Record Found');
PageUtlity.showWarning('No Record Found');
PageUtlity.showSuccess('Record Found');
PageUtlity.showInfo('You know how to search');
Lets say, you have a page, which is plugged in to custom controller, the page has search box to search for account,if user find a matching record, we will show success and if not then we show error message, clearly this is how you add the messages login in your controller

Below  is a sample message on success, you add this util class to your project and make your life easy when-ever you want to show error messages moving forward

Search Youtube in Real Time with your Voice

I was working on something interesting since last two weeks and have developed an application that search youtube in real time (meaning search as you type). It was fun, understanding how the different it feel watching youtube through new way and search data real fast. All fun started with a hack, I was doing with jquery to tweak a salesforce application, which triggered idea of real time search with video server and youtube is one single place to look for. 

After developing first prototype, I added voice search to it. It was relatively easy to add voice search to search box using webkit (only supported in latest browser). After finishing the whole application, it turns out to be real fun, specially understanding the UX this application leverages.

End of the day, it feel like as an end-user, you just say to youtube and youtube plays the video for you. The application is not completed yet and is in beta phase. I understand that my designing sense is not the best, but have a working application ready in a night hack was more than awesome feel

The code is not shared here as the application is early design phase, but I have made a quick video randomly last night, demonstrating the application