Using Force.com Integration APIs to Connect Your Applications – 1

Using Force.com Integration APIs to Connect Your Applications – 1

Richard Seroter
Intermediate Mar 07, 2016 . 5h 14m(40)

Course Overview

Salesforce.com is the world’s leading CRM provider with billions of transactions per day. It also has one of the broadest set of integration services available with options for query, batch, and streaming. How does a developer choose the right one for their situation? In this course, we’ll explore all the major integration APIs that Salesforce has to offer, and see when each one is the right fit for a given situation. You’ll learn how to use each API to get data in and out of Salesforce effectively, and make Salesforce a first-class, integrated component of your application portfolio.

Course Overview

Hey everyone, my name is Richard Seroter. Welcome to my course, Using Force.com Integration APIs to Connect Your Applications. I’m the vice president at Century Link for product, Microsoft MVP, and editor at infoq.com, author and blogger, occasional Tweeter. Salesforce continues to explode in popularity as millions of developers worldwide are building solutions on that platform. The challenge is though how do you connect Salesforce to the rest of your things? In this course we’re going to check out the many Salesforce integration APIs and figure out how to choose the right ones for a given scenario based on a deep dive into each. We’re going to cover a number of things including how SOAP and REST APIs work, how to do bulk uploads and queries of data, how do we work with real-time, push-based notifications, and change how we interact traditionally with systems. By the end of this course you’ll know exactly how the pick the right API for your integration scenario and feel much more comfortable with the breadth that Salesforce offers you. I hope you’ll have as much fun as I did on this Pluralsight course and that you’ll join me for this journey.

Touring the Force.com Integration APIs

Introduction

Hi, my name is Richard Seroter. Welcome to this course on Salesforce Integration APIs. Over these next few modules we’re going to do a deep dive into the full breadth of Force.com’s integration services. In this particular module we’re going to set up the discussion, we’re going to review each API, and we’re going to prepare our environment for all the different exercises we’ll be doing ahead (Loading).

Goals for the Course

Let’s talk about some of the goals for the course. So first of all, I want to learn the differences between the APIs. I want to make sure that you’re all getting a good sense of these very different services. Force.com has an amazing breadth of services and choosing the wrong can have some dire consequences if you aren’t optimizing your environment. I’m hoping you’re going to uncover some new interaction patterns, push, pull, real time, batch, reliable, transient, all sorts of different ways to integrate different systems, the patterns you may have used, even a decade ago, might be superseded by some things that you can do today more efficiently than you could have done before, so I want us to uncover those. And finally, I want to get deep hands on experience with these APIs. It’s very important to explore these services, so that you’re confident when working with them in the future, the point of this course is to get you very comfortable with all these different APIs, know how to use them, and be ready to use them on your next project or next product that you’re building (Loading).

Course Prerequisites

Let’s cover a few prerequisites. I want to make sure I’m setting you up for success in this course so that you’re coming in with the right expectations. So first off, I expect that you have some coding experience. We’ll be doing some light coding and reading a fair bit of code, you’re not going to write much, but for the most part I want you to be able to read code fairly effectively, which means you should be coming from a background where you’ve even done some coding before or scripting and so looking at object oriented coding isn’t going to throw you off too much. I’m going to hope you have some familiarity with JavaScript, not because Force.com requires a lot of JavaScript, and you’re not going to be doing any raw JavaScript development, but we will be using a prebuilt Node.js app and it’ll be useful if you can follow along with that. So while it’s not necessary that you’re a JavaScript wizard, I do want to make sure that you’re, again, able to read it because we’re going to be using this together. Probably most importantly I hope that you have some working knowledge of Salesforce.com. Now this isn’t a Salesforce intro, there’s other courses, from one from me included, that can get you up to speed in the Pluralsight catalog. This course assumes you can do the basics within the platform itself, you can create objects, you can fill out data, you know where the setup screens are, you know some basics about identity management. So we’re not going to be covering the basics of Salesforce.com or the query language or core apex coding and their programming language, I’m going to assume you’re coming in with some of that knowledge and even if you don’t have it, I think you’ll be okay, but just know that I’m not going to be doing a lot of intro level things in this course.

Module Overview

So what’s this particular module going to cover? Well, we’re going to talk a little bit about the Salesforce momentum as a platform. We’re going to jump right in, do some quick hands-on example, just get you into the environment real quick and try some things out. Then we’re going to review the core integration patterns, they’re ignorant of the technology, it doesn’t matter the technology, the key is do we understand some of these core patterns that Salesforce then enables through these integration APIs. We’re going to recap each integration API, I’m going to overview all of them, cover some of the core usages of each so that you get a nice intro to all of them, and that’ll set you up for all these subsequent modules where we clearly deep dive into each one. We’re going to take a look at our sample app and configuration. I built an application for this course. We’re going to be using that together. I’m not going to ask you to built it, but we will be tweaking some things and I want to get you familiar with the architecture. Then finally, we’ll obviously summarize this module and make sure that you’re set up for what’s coming up after that.

Salesforce Momentum

It should come as no surprise to you that Salesforce as a platform has a ton of momentum, it’s a platform that’s been around for years, it’s something that has established itself as a clear leader in this space and so I want to call out just a couple of things to give you a sense of the community that you’re now part of, taking this course really gets you further into this community that you should be happy to be part of, there’s over 2 million registered developers, up from just half a million 4 years ago. You’ve got 137 user groups worldwide with over 33,000 user group members. Over 85% of the Fortune 100 companies have installed one Salesforce.com app exchange app, and the number of daily transactions, it’s a point in time snapshot from when I’m teaching this course, it’ll be higher after this, but 3.5 billion daily transactions. You can see that on the trust.salesforce.com page, and you can see the sort of daily transactions that go on. There were over 230 billion transactions earlier in 2015 in just one quarter, it’s an impressive platform with a lot of traction, and so this isn’t something that isn’t up and comer, this is something that has established itself already, so learning these integration APIs is a huge part of growing in this ecosystem and making sure you’re connecting the systems that are inevitably going to bump into Salesforce in your typical enterprise.

Why Use Force.com APIs?

So why use the Force.com APIs? Why go ahead and use those at all? I’m going to really just point out two reasons why this matters. You need to connect stuff. No application is an island. You can have some identity resources sourced in one place, your user authentication, you could have data and logic sitting in another place. You might have your customer facing experience in somewhere else entirely. One of the biggest challenges and opportunities in the cloud today is building expertise in linking everything into a cohesive experience, even if the app is composed of these micro-services, your end user may not care and so you’re often in the business of connecting different things, and Salesforce is clearly a part of that for so many companies now where their data is in Salesforce or they’re using Salesforce to access data elsewhere and the key is not to treat these things as islands, but do your best to integrate them, so that your end user and your customer has a more cohesive experience and can be more productive with all of the information that sits around your business. The second main reason is to automate stuff, in essence manual is the enemy of scalability, it’s key to figure out ways to create reproducible processes that use automation to create users, synchronize data, aggregate information or simply apply consistent business rules. So really important to use these APIs to automate some things that you could absolutely do manually. You could absolutely hand key in 500 records into an object, unless you don’t really like yourself or your interns, you probably don’t want to do that, you’d rather use an automation job and do that very, very repeatedly, quickly, and efficiently. So the key is I want to connect things, I want to automate things so that I can be more productive with this platform.

Demo Description: Setting up Your Account

Let’s go ahead and jump right in. Let’s get a sense for what it feels like to integrate with a Salesforce system. So we’re going to do a few things in this set of exercises or this exercise, we’re going to create a brand new Salesforce developer account, it’s free, easy to get access to, so we’re going to all do that together. We’re going to create that account to use it. If you already have one, you could absolutely use that for this, there’s no reason you have to create a brand new one. I’m going to do that because we’re going to be adding some new objects over time and others and you might want a clean sandbox to work with. So it’s up to you if you’re like to start over again. We’re going to go ahead and view the standard objects, look at the records, get a decent sense for what’s already in there. We’ll view an individual standard object like account and look at the records in there, and we’ll go ahead and get a sense for what’s in Salesforce. Then we’re going to use a tool called Postman for API tests. I don’t care if you use Postman, if you have something else you like to use to invoke REST APIs and SOAP APIs and so forth, have at it. This is something that’s free and plugs into your Chrome browser and it makes it really, really easy to build and save your API tests for future and edit them and look at all the headings and really simplifies it, so I’m a big fan of it. You don’t have to use that for this course, although I would highly recommend it. We’re going to authenticate ourselves via the API.Most of the Salesforce APIs require you to say who you are so that your security and permissions are applied to that request, so we’ll go ahead and authenticate ourselves. We’ll call the SOAP API. There’s multiple APIs available, we’re just going to do a really simple SOAP call so you can get a sense of calling that API, getting back some results, and seeing how the API works.

Demo: Setting up Your Account

Alright we’re going to go ahead and do our first demo. So first thing we’re going to do is sigh up for a Salesforce account. If you go to developer.salesforce.com/signup, you’ll get a chance to get a free developer environment. So I’m going to go ahead and sign up for a brand new one just along with you, going to need to put in an email address because it’s going to email you a special token, I’ll say I’m a developer I guess, in this context I am. And then finally we want to give a username, should be in the form of an email address, I don’t believe it has to be, but let’s go ahead and make sure we play nice. So I will do Richard-Pluralsight@seroter.com, that does not actually exist, check the box, and go ahead and sign me up. I have to provide a company, let’s make it private, and I have to provide a zip code because Salesforce needs to know all about me. Alright very exciting, it says it did go ahead and almost get me there. If I check my email account I hope that I’m going to have some email that comes in and lets me confirm that this is indeed coming from Salesforce. Sure enough, I have an email from Salesforce developers, we take a look at that, it’ll go ahead and say my username, it’ll ask me to set my password, let’s go ahead and click on that link which will confirm my identity. Alright it’ll ask me for a password, I’ll go ahead and generate a password here to use for my account. I’ll go ahead and type that difficult password in. It asks me for a security question, I will answer this without letting you see my answer. We’re not that close yet. Alright so with that provided it’s going to go ahead and set up my account and give me my Force.com account, very exciting stuff. So here I am in Force. I can say go ahead and show me later, you can walk through a tour if this is your very first time using this, you can also switch to the new lightning experience for a different user experience. I’m going to go ahead and enable that because I do want the new lightning experience. We’ll probably switch back and forth once or twice. But I do kind of want the new hotness here of lightning. Excellent. So I switch the lightning experience up there at the top by clicking my name and choosing switch to lightning experience. All of the sudden then it will show me the much nicer interface after many years Salesforce has refreshed this and you’ll be able to use this. So this kind of sets up our account. We now have a basic environment. I can see some navigation here on the left. I can see things like Opportunities and Leads and Accounts. If I click on Accounts I don’t have any information in here right now, let’s go ahead and just add a simple record, just so when we use the API there’s actually something there. Providing some very, very simple data, saving that, now I have a simple account. So we have one account. So you just add one record so that you’ll have something. You can go ahead and switch to All as well and see all the accounts, it won’t just be the one I had, if you actually switch to All you’ll see all the default ones they give you, which is great. So we also have one we created now, so we can prove that we’re accessing this account that we just made, which is great. So I’ve got all these records. Let’s go ahead and call the API. Now there is one thing to be aware of is you want to make sure that your user has permissions to call the API. If you jump into setup, clicking the little moving gear and going to setup home, by default, any regular account may not have permissions to call the API. So we do want to make sure that as I look at my users and I look at my roles, that I’m in a profile that has access to use the API, if not then obviously any API call would fail. So I am in a system administrator profile, I like my chances that system administrators are allowed to call the API and do things like that. Sure enough, when you look at administrative permissions, API is enabled for this particular user profile, so I’m set. So if you notice you can’t get access, make sure that your user actually has access to the API through the permissions. So we’re good. We’ve gone ahead and created an account, get back to the home, the actual application from here. We can again look at the accounts through here, what can sometimes be tricky is this Recently Viewed versus All, so make sure you don’t get freaked out that you don’t have any data. So I can see there’s 13 total accounts. So now let’s go ahead and what I want to do is go to Postman. So if you go to getpostman.com and you’re usingChrome and click Get the App, what will happen is it’s going to go ahead and take you to the Chrome store and let you go ahead and install and run Postman. So go ahead and do that, install the application. Then you want to go ahead and open Postman. So you’ll see that you have an interface, you can create Collections of API calls. I created a new folder here called Pluralsight, a new collection, where we can store all of our different queries for later. When you’re in this environment you can choose your HTTP verb to invoke, put your URL here, pick an authorization scheme, manually add headers. If it’s an HTTP request that has a body like a post, I can go ahead into Body and type in a raw body of text or of XML or JSON. I can switch that to form-data, kind of like a key value set, things like that. So really, really powerful stuff. We’ll use a number of these settings over time, and then you can send the request and get the response back. Before we make the call, let’s go ahead and unzip the package of code that comes with this course. You should be able to download the demos.zip file that comes with the course. So what I want you to do is take those various pieces and what you want to do is obviously unzip them into a folder, I’ve put mine at c/Pluralsight so I can do what I need. We’re going to access the one in mod1. And so what we’re going to have is what I want you to do is go ahead and take mod1 soaplogin, we’re going to go ahead and select it all and copy it. I’m going to close this, and we’ll go ahead into this body in raw and paste that, and I’m going to switch that to XML because that’s what it is. Actually I’ll make a text XML. Now where do we want to send this to? Well I want to go ahead and do this as a post, we’re posting it to https, it’s going to be secure transport, and we’re going to send this over to login.salesforce.com/services/Soap/c and we’re using the 35th version of the API, they have many versions beyond that. So I’m passing this in, now of course this won’t work because that would be an obscure username, so we want to pick the username and password associated with our account. So I chose Richard-Pluralsight@seroter.com was my username. So what I need when I make this call is a password plus my token. The password is the value clearly we created when we set up our account. And for me this value that I set up at the time, this won’t help you now because I will change it before you use the course, is that password. Now the token, where the heck do I get that? Now we didn’t have that sent to use yet, so let’s go back to Salesforce and if you go ahead and look in your setup and you look at My Personal Information; you’ll see an option to Reset My Security Token. So we didn’t get one initially, so let’s go ahead and reset my security token so it sends me one. It went ahead and said it sent to me Richard@seroter.com, that’s great. And you’ll see that you append that to the end of your password, that’s the total password you use in the API. If I go back and look, I have a new security token, I’m going to go ahead and save that value and I’m going to go ahead and replace the plus token in my request with that value. So now what I have is I’ve got a request to login.salesforce.com, I’ve got a raw XML body that we pasted from the mod1 folder to Richard-Pluralsight@seroter.com, I’m going to click Send. That was quick, let me go ahead and scroll dnw. I’m missing an ht, oh my SOAPAction header, how dare I. So let’s go into the Headers and we’re going to type SOAPAction and just two, what this value is is just a couple of single quotes, I don’t actually need to provide anything detailed there. And sure enough, now when I call I get back a login response, and we’ll talk more about these objects later. The things to care about here is I want to know the server URL, I’m going to use this value, so na30 is something that’s going to be important to me, and then very important is also going to be the session ID, this is a short lived token, and we’ll talk about this later with the SOAP API, that I can use to log in. So I logged in successfully, I proved that that worked. So now all I want to do is create one more request, I can click that tab and let’s play it safe, let’s go ahead and save this request. So now I can do this over and over again and not have to start over, so let’s save this in the Pluralsight folder,let’s call this SOAP Login, so now I have it forever, and I can just easily use that over and over again. Let’s have a new tab, and what we want to do here is actually go ahead and get a list of accounts. So here we’re going to be doing a Get and I’m going to want that login address again or the address of my things, so let’s go ahead and scroll down and I’m going to need this serverURL, this is important to me, so I want to save that, that first part in this new request, I’m going to be doing a Get to that URL. And then what I’m going to want to do is, I’m sorry it’s going to be a Pot to that address, the body we’re going to get once again, it’s going to be raw, it’s going to be XML, and we’re going to get this from the folder of our code here. So go to this folder, you’ll see soapqueryaccount. Open that up, copy it all, select it, close that, come back to Postman, paste that in, and what we’re looking for here is the token. So go back to SOAP Login and you want this value called sessionID. If you can memorize this and you are a weird genius, and that’s awesome, but for the rest of you, copy and paste it.Let’s go ahead and put that exactly where token is, that’s the secure value that says we’re allowed to call this and here we have a query. Select the ID and the name from the Account object. Again, we’ll talk about this more later, but you can see, here’s a quick basic request.Paste that in, we have our session, let’s click Send, and sure enough we get the results back. It shows me some header info, but then it shows me the result. Here’s every account, here’s every ID including the random one we created ourselves, Vandelay Industries here at the bottom, 13 results, so we were able to call the API, get back result, authenticate ourselves of course, and still get that result back from account. So let’s go ahead and save that for future use, we’ll add that to our Pluralsight connection and call this SOAP Query Accounts. And now again, you have this for further use as you want to keep exploring the API. So we were able to login, query accounts, and start using the SOAP API and the API in general, thanks to Salesforce.

Force.com Integration Patterns

We just finished our first demo, creating a Salesforce account, authenticating that user programmatically, issuing a request for a bunch of information about accounts, and so now you’re a Salesforce integration developer, congratulations, go update your resumes. But of course you want to learn some more, so let’s talk about the actual integration patterns that underlie many of these different APIs. So there’s a very good paper from Salesforce called Integration Patterns and Practices, and it points out four patterns that we’re going to highlight here and talk about a little bit. For an overview, what are they? They are remote procedure call – Request and Reply, this is where Salesforce is invoking a process on the remote system and waiting for the result. There’s remote procedure call – Fire and Forget. This is where Salesforce is also invoking something in the remote system, but it doesn’t wait for the response, it’s asynchronous. There’s Batch Data processing, data is stored in force or it’s in some other system, and I’m pulling data into Salesforce or pushing data out with bulk data on a schedule or a regular rhythm. And then finally Remote Call Ins, this is what Salesforce calls the idea of external systems calling into Salesforce to grab data, create records, do whatever it needs to do, but the remote system is treating Salesforce like a system of record that it’s invoking. All of these things kind of factor in as data integration, they could be process integration scenarios. Next up let’s actually dig into each one of these in a little more detail. So let’s drill into these just a little bit more, so Request and Reply, it’s a synchronous call to a remote system. When I implement this, Salesforce is the one making the call to the remote system. It’s usually initiated by some sort of event or batch, you know, I could do a request and reply in a batch fashion or something triggers it that, hey a record change so now I have to call this remote system to update some data or I have to look up some information or update an order status, whatever it is, something is initiating it, that or either some sort of batch request where a bunch of things just changed. When you’re working with this you have to think about the response and how do you store the state. When I’m invoking this other thing and passing some information in, I have to think about how do I take that response, where do I store it, am I storing it on an object, am I using that data real time? What am I doing with the response of that data? It requires you to think of idempotency or this idea that I could invoke an endpoint multiple times without actually causing a change to the result. So imagine calling post multiple times on an endpoint, passing in an integer and not actually incrementing it that many times, but the system is smart enough to make sure that it either detects a duplicate or by calling that endpoint over and over again it doesn’t actually change the result. So those endpoints have to be smart enough. And then finally some careful security, but being sure that I have securities for those calls outside of Salesforce. How am I authenticating into this other system?When we think of Fire and Forget, this is an asynchronous call to a remote system. Again, when you’re doing this Salesforce isn’t waiting for a successful completion, everything just continues on. This could be initiated by a user or system event, something that I need to trigger based on something happening in the system and I want to go ahead and now initiate some other process, maybe it initiates an ordering process, maybe it initiates a hire or fire event because an employee record changed. Whatever that is I don’t need to wait for the result of it, I can continue without it. You have to ask yourself though, do I need guaranteed delivery? One of the benefits of Request and Reply scenarios is I’m waiting for a response and if it doesn’t come, I can do something about that. In Fire and Forget, I am sending a message off and maybe it got there, maybe it didn’t. I don’t know for sure that it reached it because I’m not waiting to get that acknowledgement in the same way. So as you think about, do I need a sort of guaranteed delivery? Do I need to know it made it? Or do I need to know that it processed successfully? That’s an important thing to think about, that may impact which choice you have. You have to think about how you handle the response. When it is going to come back? How it is going to come back? What happens when it comes back? What if the process moved on within Salesforce and now I get this unexpected message as a response from something I invoked hours ago. What am I supposed to do with that? When we’re thinking about Batch Data Synchronization, you’re going to think about this when I want to do an initial load into Salesforce. I want to load data into Salesforce onto some sort of weekly basis. Or I want to extract data from Salesforce into some on-premises data warehouse that I have. So the question is how do I import or export this data effectively in a way that’s going to be the smartest way possible? And so I’m dealing with large amounts of data typically. I’m not going to use batch processes when I’m processing a single record, it’s when I’m thinking of doing this with dozen, hundreds, thousands, millions of records. This could be an initial load or an ongoing load. So it could be the first time I start using Salesforce I’m going to do an extract from my old CRM system into Salesforce and get going, or it’s ongoing where every hour, day, week, month, I need to do a data synchronization back into a master customer store that I have on-premises. Whatever that would be, you have to think about the frequency as you think about this. You want to optimize that refresh schedule. If I’m calling, I don’t want to call this every hour or every minute, it’s not going to be smart. I’m going to want to think about what is the right frequency to use this sort of batch data synchronization process? You also need to think about post processing. We’ll cover this a lot more later on, but what happens after I load the data? Are there a bunch of workflows or triggers that fire? Do other data records get updated when one gets inserted? All of those things to think about, what is the lifecycle of that batch process? And we’ll touch on this later, but avoiding contention, you could hit a point where you’re really overloading an individual record or record type and actually creating locks in the system. So you have to be careful as you’re doing batch data synchronization that you’re not hurting the people that are on the application right now trying to use it for their day to day activities. And then finally Remote Call-Ins, how does a remote system connect and authenticate with Salesforce to update or use existing records? External systems are interacting with Salesforce. So think about those source system characteristics, can it handle a contract first SOAP interface or is it thinking about REST and more mobile clients? Is it something that is rich enough to do reliable messaging or is it very simplistic? What are the sort of volumes I’m dealing with? And so those data volumes are also going to dictate maybe how I do this, how do I connect and authenticate and update Salesforce? Is it real time? Is it batch? How much data am I dealing with?

Force.com’s Integration-related Services

There are no shortage of ways that Salesforce makes it easy to integrate with their platform. There’s a lot of different integration related services that you have at your disposal. There’s REST API, SOAP API, you’ve got things like Lightning Connect and the Data Loader Tool.There’s a Platform Cache if I want to load data in from an external system and use it inside. There’s External Objects where you can store data from an outside system. The Streaming API, Outbound Messaging, Apex Callouts. We’re going to focus on six of them in this particular course, the REST API, SOAP API, Bulk API, Streaming API, Apex Callouts, and Outbound Messaging. But lots of different interesting ways if you’re interesting in the others when we get done with this, continue to explore that. The key is there’s a lot of services, you don’t want to just default to one of them. Let’s look at the six that we’re going to care about in this course. First off, there’s the SOAP API. Just a few things to know about, and we’re obviously going to have a whole module on this, but it’s enterprise friendly, it’s meant for integrating with enterprise systems because of the fact that it has a WSDL, which is a Web Service Definition, but it makes it easy to talk to these systems, generate stubs, it’s something that a lot of enterprise apps already are prepared to integrate with from a SOAP perspective. It’s got a really good coverage of UI capabilities. You have a lot of different things, not just dealing with objects, but dealing with resetting passwords or sending emails or doing all kinds of other things in Salesforce, you have a lot of functionality in the SOAP API.There’s a lot of WSDL interfaces, this is the Web Service Definition Language, a couple of different ways that you can integrate with these systems or define that SOAP endpoint, whether it’s a more strongly type or weakly typed object, we’ll go into that in depth, but you have a few different choices for how you want to use the SOAP API. It is entirely XML-based, so if you’re a fan of XML, don’t have to apologize for that, you can embrace the SOAP API as your choice. The REST API, this is a going to be a little mobile, web friendly because you have lightweight communication, smaller payloads, you have different authentication schemes, it can be a little friendlier to sort of modern app development, whether it’s mobile or web or not, it’s a simpler interface to deal with. You have some pretty nice composite operations. We’re going to play with these in the course. This gives you some interesting ways to bunch up calls and do some related calls or even unrelated calls in a single request, so that’s pretty nice. You have a nice standard interface. What I mean by this is you’re working with the HTTP verbs, get, post, put, delete. It’s a very logical interface, versus SOAP you often have methods and operations that are contextual to the app you’re talking about, get account, update this particular thing. They have very verbose names, there’s not just the standard interface that you deal with, versus REST is look, I know when I issue a get request to this URI, I’m going to get back a resource representation for that object. It’s very clear I don’t have to understand anything different there. And you get JSON support. So I could do XML or I can do JSON. It’s very easy to switch between the two, it doesn’t really matter. So based on what language you’re dealing with or which environment you’re dealing with, you may choose to use one or both when invoking the REST API. When we think about the Bulk API, this is for bulk loading of data. I’m going to insert lots of data in CSV or XML format, even binary content, like attachments. I’m going to do that with bulk loading of data. What’s cool is I can also issue bulk queries, so I can issue a request that will later return lots of data. Hey go ahead and get my something that might return 10,000 records, I probably don’t want to do that threw a web service interface. I can do that through the bulk API. And as you can imagine, it’s all asynchronous, I can submit jobs, get the results of them later. Whether that’s inserting a bunch of records or upserting or deleting or retrieving, it’s all asynchronous, I’m not holding a threat waiting for all these things to happen. Outbound messaging gets us more into an event-driven messaging. I want to have a real time push when data changes.I don’t want to just pull an API into perpetuity waiting for something to happen, instead I want the system to tell me that something has changed. This gets into a very exciting way of dealing with systems versus treating them as systems that have to keep asking something, instead my system is telling me something. It’s asynchronous, but the key is its reliable delivery, or at least pretty reliable that it has queuing built in, some built in retries and visibility into the retries, so that while it’s asynchronous and it’s fire and forget, it is waiting to see if that message at least arrived at its destination and if it didn’t it can queue up and try again. The key though is the receiver has to be internet-accessible. Salesforce has to be able to see that endpoint. So you can’t receive this web service message somewhere deep buried in the nest of firewalls in your corporation, instead it has to be something that’s internet facing. The Streaming API is similar in that it’s also event-driven messaging. It’s the idea that real time changes are streaming to a listener somewhere else. It’s asynchronous, but not reliable delivery. There are some ways now, very recently, that make it possible to do some replays of events, but in essence this is something if you’re not listening to the stream, you’re not going to see it. Consider it a lot like Twitter, that I can go ahead, if I’m not watching my Tweet stream, I could miss something go by. It’s not something that’s going to guarantee I’m going to see it. I can do replays potentially, but it’s not the same thing as an email where if I’m offline and I come back online I’m going to see everything there, I’m not going to miss anything. Where this differs from outbound messaging is that the receiver can be behind the firewall because in reality this is using a pull-base that looks like push-based. So in my application it feels like I’m getting this pushed, but because it’s actually using a pull it could sit behind your corporate firewall and it does not have to be internet accessible. Finally, let’s talk about Apex Callouts. This is the idea that I want to be able to call out to other systems from Salesforce. So I can generate code stubs, if it’s a SOAP endpoint I can generate something based on a WSDL, makes it very, very easy to call that. I can also, if I want to, mess around with raw HTTP and those XML or JSON payloads. So if I don’t want to use SOAP or I want to have more control over the payloads, I can actually work with raw objects within the Salesforce programming language. There’s some nice credential management that’s recently become available, so this lets you use name credentials to give you a more secure configuration. So we’ll take a look at this as we move on, but this is a nice way to securely call out from Salesforce to other systems. There are also some nice long running options. If I’m in the Visual Force page and want to do a long running call out to some external system and integrate with its data, I can do that and then call back so my user isn’t sitting waiting for a page to refresh for a long period of time. Very nice, we’ll do a demo of this.

Overview of Demo Application

Alright, so what are we going to work with in this module and set of modules in this course? We’re obviously going to be working in Salesforce directly for some of this, but I’ve also built an external app that we’re going to get to mess with and you have the source code for in your download package, and we’re going to mess around with this Node.js application. What it really is is it’s meant to be fictitious, you can’t commercialize this, I guess you can, you can do whatever you’d like, but the idea is that I would use this external app to view voter info that is stored within Salesforce. So I’m going to build a Salesforce app that’s based around voter information and donations. And so this external app wants to call into Salesforce, pull information out about voters and maybe show that to someone who’s walking door to door or using an application within a precinct, whatever you’ve like to do. I can review some of the donation history of that particular voter and see what’s going on there. I could monitor some outreach efforts, hey did we talk to this person recently and when was it? So behind the scenes this is a set of services. You have one web application, voter tracks, you’ll see in your folder, one component in there that receives an outbound message, you have another app that does streaming, and you have another app that we’re going to call out from Salesforce via a callout. So in Salesforce itself, again, is the one that’s storing all the voter information, it stores a donation history, it tracks if we’ve talked to someone, but this external system is often interacting with Salesforce, so we really get to see what an integration can look like.

Demo Description: Setting up Your Environment

So now let’s do one final demo here in this module. This really sets up our environment perfectly for the rest of the course. So what we’re going to end up doing is building three custom objects. Again, this is a great part of Salesforce is I’m not just constrained by whatever objects really, again, objects being the issue if you think of it like a database table, I’m not constrained by the ones they’ve given mebecause odds are that’s not going to meet my unique business needs. So what I want to do is I want to create three of them, I want to create an object to represent a voter, I want to create an object to represent that voter’s donations, and I want to do one to represent the precinct that voters are associated with, so I can do queries based on the precinct and see who comes back. I’m going to load a quick record into each of those custom objects just so we have some base data, of course we don’t want to do a lot of that manually as that defeats the purpose of APIs, but I want to start off with a simple record in each one. Then we’re going to confirm that you have Node.js as a platform installed locally. Just go ahead and you’re going to want to download that and run that so that we can actually just turn on our sample app and make sure that it works okay. So by the end of this particular demo we’ll have created some custom objects, we’ll make sure that our custom app runs, and then we’ll be all set up for all the following modules in this course.

Demo: Setting up Your (Salesforce) Environment

Alright I want you back here in your Force.com account that we created a few moments ago, so now we’ve got our account. What I want to do, as we talked about, is we want to create three different custom records. So let’s start off by going to the little gear over here, getting into the setup experience, and this is where we can create new objects. I’m going to go ahead and shrink this just a little bit, and you see Objects and Fields under Platform Tools. I can expand this and see Object Manager, Schema Builder, also note that the quick find is very good. So if I know I’m searching for Object Manager, I could also just type for that, if I don’t know exactly what submenu things are under. Let’s go ahead and click Object Manager. And what we’re going to want to do is we can see all the built in objects that we have here. I can see Accounts and Campaigns and things like that that Salesforce precedes your account with. And that’s going to cover in many cases a lot of the things you need, but we want to do a little more than that. So I’m going to create a custom object with the little Create button, and then we’ll be asked a number of things, what’s the label? What is this thing? And so we want to call it precinct. Its plural would be precincts and the object name will be precinct. There we go. Precinct Name is a value of text, that could be its record ID, record label if you will. All the other settings we’ll keep the same and click Save. You’ll see the API Name is Precinct__c, we’ll use this a lot later, and you’ll see there’s settings like can I use this with Bulk API, can I use this with the Streaming API? A lot of properties and settings that you still have a lot of control over. We can also see it has Standard Fields like the Created By, things that are basic, and then a field called Precinct Name that’s mapped to the actual name field. Let’s again go up to the top right and click Create and choose Custom Object. Now we want to go ahead and create the Voter, plural would be Voters. And once again we’ll let Voter Name be the Record Name label, that’s fine. We’ll click Save, and we’re going to want to add some additional custom fields to this, once again, it’s called Voter__c. We’ve got some standard fields here, but we’re going to add some custom fields, so let’s click New for Custom Field and let’s add a few things. So I want to add a checkbox field type, pick Checkbox, and this is going to be a field to tell us whether or not we’ve contacted this person, that we’d want to know, have we contacted them for 2016’s next election (Typing). So in this case I’ll have a checkbox, its default value is unchecked, we haven’t talked to them yet in 2016, the Field Name gets converted to something that Salesforce can store as a field name, so it turns it into an underscore, gets rid of my parenthesis. Click Next. I’m going to go ahead and keep everything the same,nothing fancy to change there. We’ll do Save and New because we want to do another field. We want to do the last contact date and I’m going to make this a date, so let’s go ahead and find the date type, scroll all the way to the bottom and click Next. What’s the name of this? This one’s going to be Last Contact Date. So this will be the last time we talked to them. We’ll do Next and Next, and we’ll do Save and New as we’re going to add another one here. Next we’re going to have a mailing address and there is an address composite field, but let’s not make life so easy, let’s go ahead and make this of type text, click Next. This is going to be Mailing Address. The length, we’ll make it 200. We can do some other stuff, make it required, define unique values, don’t need any of that. Let’s go ahead and click Next, click Next, we’ll do Save and New, a couple left. Alright so now we want to do the political party that they’re part of, that they’ve registered as.So what we want to choose is a Picklist. Then we’ll be asked to actually choose the values in the Picklist, so let’s click Next and we’ll call this Political Party and then we want to enter the values. Now based on the country you live in, you might want to do different values, these are the ones I used and mapped some of the data to, but nothing prevents you from technically typing in your own values. So we’ve got a few values. Click Next, click Next, and Save and New for the last one. So the last one is now I want to map this voter to the precinct, remember we created a precinct object, so I want to define this as a Master Detail Relationship where technically the master would be the precinct and this voter is the detail. So it relates to what? Well it relates to precinct. So I’m going to tie those two records together, and I’ll click Next, Field Label is Precinct, Field Name is Precinct, Child Relationship Name is Voters. There’s a read/write relationship, that sounds fine. I could allow reparenting, so that you could move things around after the fact if you wanted to. Next, and then we’re finished. This object then is complete. So we’ll just click Save. So we added on Voter, if we scroll down lots of custom fields here. I can see Precinct, Contacted, Last Contact, all the things we talked about with a Master-Detail relationship on Precinct. We have one Custom Object left, let’s go ahead and create a Custom Object and this one’s Voter Donation. With Voter Donations, of course, being the plural. So Voter_Donation is the actual Object Name and in this case what I want to do is I’m going to go ahead and also just switch this DonationId, so we can change the name, kind of the unique thing, and we’re going to make it Auto Number so we don’t have to provide it, the system can go ahead and do that for me. And let’s go ahead and make its donations, we’ll start it with DN, we can actually define a mask here, and we’ll start it at 0. We’ll click Save and now we want to create a couple of custom fields on this. So go down to Custom Field and Relationship again, click New, and I want to have a few things. I want to have currency because we want to match the actual or list the donation amount, so let’s go to Currency, click Next, and we’re going to name this field Amount. Then you could have a length and the decimal places, it could go up to 2, so let’s make it a 10 and 2 sort of field. We’ll click Next. We’ll click Next, and we’ll go ahead and do Save and New. Next we want to have the candidate’s name, this can just be simple text. In a real life you would probably link this to another record type and a record would be called candidate and you would have a master detail or some sort of lookup relationship, that would be fine. In this case we’re going to keep it easy and just have a text field called Candidate Name and make this 100 or make it 50, their names won’t be that big. And we’ll do Next and Save it all as is. A couple final field types, let’s click Save and New and we’re going to have donation date, when did they make this donation? I need to know that because I might want to do queries to pull all donations within the last year,or things like that, so it’s nice to have the data types on here, don’t just mail it in and do them all as text because then you’re not able to do as many interesting things. So we have Donation Date, let’s click Next and Next and Save this, and then finally what we’re going to have is a field called Voter and this is going to be a lookup field. So I want to have a Lookup relationship, not Master-Detail, I just want to have a Lookup where I look up to the donor, and we’ll talk more about these later. So what does it relate to? It relates to the voter. So the voter donation, I can look up a voter to tie it to. I can require that field. I can do things like that, so if I choose to I can make that a little tighter, if I’d like to and not even allow deletion, if it’s part of a lookup I can do some things to encourage a tighter relationship between the two. Let’s click Next and Next and Save. Alright, so we’ve got all of our object types. So we’ve created these objects, now we need a way to actually enter data into them. They don’t automatically show here on the left nav. This will become customizable very soon. It’s not at this exact moment that I’m recording. So let’s go ahead and make sure that we can see these records and be able to add some quick data to them. The best thing to do is go into your applications and you can see it’s not listed anywhere here right now, if I go under Sales I don’t see Voters, I don’t see Voter Donation, so I want to be able to get it into these applications. I could also create an entirely new one. So let’s go ahead into Setup and from Setup what we want to do is create some custom tabs. So let’s go ahead and click Tabs, search at the top, go right to Tabs, and we’ll say we want to create some Custom Object Tabs. So this is really easy, click New, click the object, we want to have one for Precincts, you have to pick a style, this couldn’t matter any less but the time being just go ahead and pick something, I’ll pick the globe. Go ahead and click Next. You choose which sort of profile should be able to see it, I’m fine with virtually everybody. Click Next. Then you choose which app and so if you create a custom app it would show up there. In this case we won’t create a custom app, we’ll just add it to ones like the sales app and things like that, so we’ll click Save. Let’s add another new one and let’s set this for Voter. For this one let’s go ahead and use the people icon here. Great, click Next. And we’ll save this one after opening it up to the all the profiles and adding it to every app. Again, you can imagine, you probably choose a specific one to add this to if you really cared long term. And then finally Voter Donations and let’s pick a tab style here that uses some money, and we’ll go ahead and here use the treasure chest, that seems to make sense, and click Next and Next and save it. And so at this point now when I go back to my app what I should see, if I go back to my app launcher here on the top right, if I click on something like the Sales app, I should now see things here at the bottom for my three things I just added. So let’s go ahead and add some data. What I want to do is let’s make this really easy, what we want to do is add some data for just one record, so we just have something in our thing, so we don’t have anything in Precincts, let’s switch in All, sure enough nothing there. So I can click New. And if you remember we made this really, really simple, so we’ll just make this 3rd District, it’s the 3rd district for voters. Click Save. And fantastic, we now have a precinct. So making that very easy. Let’s go back and now let’s add a Voter to that particular one, click on Voter, sure enough nothing there, let’s click New. I’ve been watching a lot of Parks and Recreation lately so you’re going to have to tolerate all of my names being from that show, Leslie Knope, she was last contacted let’s say never, I don’t careabout that data point just yet. For her mailing address, she lives somewhere near me in Washington. We’ll say she’s a Democrat, we’ll pick the Precinct, as you can see it’s a pick list because we chose that relationship there, it’s not free text, so I’ll go ahead and pick the 3rd District and then click Save. Fantastic, so now I have a voter, I can look at related and I can see that it’s tied to donations, whenever I have one, which is great. But let’s go back to the original way to create the donation. I’ll go back to the app launcher, click on Sales, and then finally I want to go to Voter Donations. I’ve got no donations so far, let’s go ahead and click New and she’ll donation $100 to Gary Gergich,donation date we’ll say was in 2015, and which voter, again it’s a dropdown, I can pick Leslie, and click Save. So now I’ve got a voter donation, I can see that’s related to a voter or if I go back, rather, I can see if I go back to the voter and we check out Leslie, I can see that she is tied to a specific donation. If I check out Leslie and check out her related, sure enough she’s got one voter donation. So now I’ve got data in all of them.

Demo: Setting up Your (Development) Environment

The last thing I want you to do in this exercise to set you up for the rest of the course is make sure your app can run. So go to the Node.js site, this is Node.js.org, and download the latest. Now I’ve built and run this course using version 4.2.6, there may be a newer version by the time you take the course, probably should be fine, but just keep that in mind. So whether you’re on Windows or Mac or Linux, go aheadand download your latest version and install it. This should also put it in your path and you can confirm that by going to a command prompt. In my command prompt I can just do node -v and I can see I’m running version 4.2.6. Next I want you to download a code editor. Now it doesn’t really matter, as I said, we’re not doing a whole lot of coding, I like Visual Studio Code, it’s free, it’s cross platform, it’s very easy to use, so if you’d like go ahead and download from code.visualstudio.com, run that on your platform so that then you have a nice little code editor that has some good features, debugging, things like that. So go ahead and do that. Then go ahead and open that. When you do, you’re left with an open environment. What I want you to do is I want you to open a folder and I want you to jump to the Pluralsight directory wherever you unzipped your things, and so there’s an app at the root called VoterTrax. When you click that then select that folder and then Visual Studio Code loads that folder into here. And so here’s the code for our particular application, again, you don’t have to do much with this, I’ve built almost all of it. The only thing I want you to do in this exercise is prove that the app can run. So before you do that, I purposely did not include all the different modules in the zip package or else this would have been 50, 60, 100 MB, I like you more than that. So what you’d have to do is tell Node.js to take all of these dependencies and load them now when I need them.So go back to your command prompt, so I’m going to get to the VoterTraxApp and once you’re in there simply type npm, this is the node package manager, and install. What it does then is it looks for that package.json file and it sees anything in there and it takes and goes and finds those dependencies from the registry and loads them in. So this makes sure that you have everything on your local machine that you need to run the application. This is pretty straightforward, it does all of its magic. You can confirm it works by going back into Visual Studio Code and you should have a folder now called node_modules, and these are all the different modules and this is typically pretty large. So the final thing is you switch to this little icon called debug in Code and if you’re not using Code then you could go back to Visual Studio or rather your command prompt and kick off the app from there, but let’s make life easier for ourselves. We want to run this. Now the first time it’s going to say, what type of app is this? It’s a Node.js app, so it builds a little manifest that tells Visual Studio Code how to run this, how to launch it, which file to launch, when it starts it up. It’s launched our app and I should be able to go into the browser and hit localhost:3000. If you do that and everything worked right, you should see the home page of this. Now nothing else will work yet, right, because we haven’t plugged it into the app, but this shows you that you’ve installed node correctly, that you’ve got your app up and running with all your dependencies. If you go back to Visual Studio Code you should see no errors. So if you’ve gotten this far then congratulations, you’ve got everything set up, you’ve got your account set up, you’ve got your objects created, you’ve got your objects loaded with data, and now you’ve actually got the app running that we’ll be using for the rest of the course.

Summary

We just finished a fun exercise, getting everything set up. If you went ahead and skipped ahead through this module just make sure you’ve done those demos so that your account is set up appropriately. We did an overview, we talked about what this course was going to cover in general. We jumped into Salesforce momentum, that this is a giant platform that is growing rapidly, every single day and so you’re really part of a pretty exciting ecosystem when you’re working with Salesforce. We jumped right in and did some hands-on examples, so you were able to do a SOAP call and do a call against a web service endpoint, authenticate yourself, and get back some data. We talked about some of the generic integration patterns that you’re going to see realized in these Salesforce technologies. So most of these APIs, really all of them, map back to one of these core integration patterns. We then recapped each integration API, we talked about SOAP and REST and the Bulk API and we talked about being able to do Streaming and Outbound Messaging and then Apex Callouts, talking about each, and when they’re a fit. Finally we looked at our sample app in the configuration. We saw that we have this Node.js app, we configured our application in Salesforce with custom objects and custom data, and now we’re really set up well to mess around in the rest of this course with those APIs. I hope you enjoyed this module. Next up we’re going to jump up into the SOAP API and really get hands on. I hope you’re excited for this course, I am, and we should have a lot of fun learning how to use some of these new and classic APIs that Salesforce offers.

Using the Force.com SOAP API to Integrate with Enterprise Apps

Introduction

Hey there, my name is Richard Seroter. Welcome to this next module on connecting to Force.com through APIs. This one’s focused on the SOAP API. In the last module we did a pass through all the integration APIs, set up our environment for developing against Salesforce. So if you did skip through the last one, no worries there, but make sure you did run through those demo exercises because we set up our account, we created some custom objects, we loaded some data in there, and so you want to make sure you’ve done that so that you’reready to go for this particular module. So what are we going to do here? First of all, we’re going to talk about just the basics of a SOAP API call, so we all get on the same page about that. We’ll discuss authenticating users. What does it mean to secure yourself and secure your accounts for getting in there and calling APIs? We’ll talk about the web service definition that is applicable for SOAP users in Salesforce. We’ll talk specifically about some of the SOAP actions and the objects, what makes up the payload and what are we talking about when we’re talking about the objects? Exceptions happen, so how do you handle exceptions? What are you supposed to do and what sort of things come back to you as a user when something fails? We’ll review SOAP headers, how you can use SOAP headers strategically as you’re making calls and trying to do certain things with the API and do some more specialized things with a particular request. We’ll talk about the power to create custom SOAP services within Salesforce. Sometimes the out of the box services don’t give you what you need exactly, but Salesforce makes it possible to build new services and expose them as SOAP to your clients, and we’ll build one and actually consume one. We’ll discuss the API limits, how many calls can you make, certain payload information, that you want to know those things because you could accidentally get yourself in trouble if you’re doing things at a high frequency or with certain data types or too much data and all the sudden you’re getting shut out of the system. And then finally we’ll talk about monitoring usage. How can you keep track of what you’re doing in the environment? We’ll summarize, of course, at the end and recap what we’re learned here. So for most of these modules I’m just going to start with a really quick definition, what is the SOAP API? Well it’s simple SOAP protocol access to Salesforce data and functionality. SOAP has been around for quite awhile now, really one of the first real web service definitions, we can argue over drinks one night of whether this got too fat and bloated for its own good back in the 2000’s, but nonetheless, this became a really standard interface that had a lot of things added to it over time, different sort of definitions and standards, but at its most basic it’s about transmitting XML over a typically HTTP, although it could go over other channels, and it’s meant to be a descriptive sort of language where it’s not using HTTP features, it’s typically more encapsulated in the payload.

Decomposing a SOAP API Call

So let’s take a look at a sample request, you’re posting to really a single endpoint here, you’re not really posting, not like REST where you’re hitting different endpoints for different resources, you’re posting to one endpoint whether you’re getting data or putting data or retrieving or updating, deleting, you’re always posting. You’re typically passing a content type of text XML; you’re typically dealing with a SOAP action that is empty, although you can populate if you’d like to. So it interacts over HTTP POST. It’s all XML payload, you can’t be sending JSON over here, you’re not going to send CVS content, it’s very specific to that and a SOAP message itself is big, it’s occasionally considered a little overweight as it has a lot of namespaces and headers like envelopes and things like that, but it’s meant to be verydescriptive and machine readable. Sometimes it really doesn’t matter if it’s a little extra bigger because it’s fine, it’s being read by a computer and it’s very descriptive. So you end up with a SOAP wrapper. It’s secured with a session header, so when I make a request, let’s say I’m querying data, I’m doing things like that, I pass in the session header and so that goes into it and that’s how headers are done. These aren’t HTTP headers, they’re headers within the payload, and so this is where I would actually be securing that. Most everything in the SOAP API is synchronous, so you’re always doing requests, getting a response back from this, and getting it back as an XML SOAP message.

When Do You Use It?

So when should use it? I’m going to do this for each module as well. When you use this you’re integrating with enterprise apps, and I say that because it’s typically that a lot of classic enterprise apps are built to consume SOAP endpoints or they’re friendlier to SOAP, they expect this sort of thing, they expose their own SOAP endpoint, and so more modern systems don’t necessarily have that constraint, but as you’re dealing with applications that were built within the last decade, you often are dealing with something that’s friendly to SOAP. Many tools can auto generate things based on SOAP, and that’s when you want generated objects. It can be nice. When I want to point my code language or code tools to a particular WSDL and generate some strongly typed objects that know how to talk with that, that is convenient, and it can be convenient to enterprise apps that want to work with it or for developers who don’t want to deal with raw HTTP messages. You use it when you require the broadest functionality across Salesforce. When I want to access the most functions, whether it’s accessing things around users or around objects or around metadata, the SOAP API still seems to have the most, as I’ve looked at, you can do the most things with it. So when you have a lot of needs to programmatically interact with Salesforce, the SOAP API probably gives you the best coverage.

Authenticating SOAP API Users

Let’s talk about authenticating SOAP users. How does this work? So first off you acquire a session ID from the login API, we’ve seen this a little bit so far. We’ll do this again in a moment. But you pass in your account credentials. And so you get this session ID and it’s a short lived token, it doesn’t live forever, it does expire at some point, so if it’s not being used it does actually time out after I think it’s 120 minutes or so, so it is something that’s not meant to live forever. You’d want to refresh it. You can also sign out and purposely expire that token if you would like. What’s nice is all your user, object, field security still applies here. So it’s not like when I use the API it’s the Wild West and I can do anything I want and it doesn’t matter what my permissions are. In Salesforce the API fully respects all of my access permissions, my sharing rules, my user permissions, all those things purposely get reflected here. So that an API user is the same as a user logging into the console. You can also do some things around source IP filtering. So I can filter access to say that only this source IP or range is allowed to access my account in Salesforce. This is handy if I have jobs or processes that run within my company that interact with Salesforce, but I really shouldn’t be using that API from home or somewhere else. So when I apply those source IP rules, that also applies to API users. So let’s look at an example, there’s the payload on the left. This is when I’m making a call and then getting back the response, that’s the two payloads here. So I issue a login request. As you can see, the SOAP body has an object called login and I’m passing in the username plus the password plus token combo. You may have remembered we did that in module 1. So that’s what I send in. I provide that password and the token, as I mentioned, that’s the criteria that I’m passing in, that’s how I authenticate. So I do have to know that information when I’m calling the SOAP API, we’ll see a different model with REST. SOAP does require explicit knowledge of the password.What I get back is a couple things that are interesting, so that login result you see in the payload coming back, I get back the server URL. So this is the URL I should be using for my API calls, it will be different between yours and mine in many cases, so it depends on when you created your account and otherwise, that’s what you want to know you can use because that’s going to be specific to your account. And then you also get back that short-lived session ID, so indeed it is 120 minutes, 2 hours, so you can configure that, you can actually change some things as well, that’s the default. And so the inactivity timer gets set to 0 every time you make a call, so if it’s at 109 minutes and you make a call that time goes back to 0.

Two SOAP API WSDL Options

There are two types of the SOAP API WSDL, two main types, and so we’re going to cover them quickly here because you’re choice of those does have some implications. I can choose the enterprise WSDL and that’s the first choice. This is strongly typed. So every built in standard or custom object gets represented in that WSDL, even any custom sort of operation, things like that, that that WSDL is meant to be a representation of your organization, your account. So very strongly typed. I can actually read that into my tool, generate objects, and know that an account object has a name or has a company or things like that. That makes it fairly easy to use, is that, look I don’t have to think about a lot, I can just reference that WSDL, generate some code, call it, I know it represents my objects and anything else, that makes it very handy. And so it’s great that it has the custom too, if it was just standard objects that would be useful, but the fact that when you build your own objects it still shows up in that enterprise WSDL and I can consume them the same way the standard, that makes it really convenient. This is ideal when I have a single organization solution, when I am writing code against my organization or my partner’s or customer’s organization, that’s when this makes a ton of sense. The alternative is the partner WSDL. The idea here is that this is that this is weakly typed, you’re dealing with the raw s object, which is really the underlying type of every object, and so you’re dealing with it as an s object type. This gives you the most flexibility because now I’m not coupled to one organization’s objects and structure and I would call other APIs, like the describeSObjects API to actually find out what the structures are. So as you can imagine, this is, again, must more flexible because I could call that describe API, find out what objects are in there, and then be using this weakly typed thing. What this is handy for is when I have apps targeting multiple orgs. So if I’m a partner and I’m selling something or even if I’m just trying to be very, very flexible with my own organization because things change all the time, I could use this WSDL and just do some runtime level interrogation of my objects to find out what’s in there. Again, your code has to be much smarter here, your logic has to be much smarter here because I can’t just fall back on known types, but you get maximum flexibility. How do I see my WSDLs? Consuming them is pretty easy. You actually can go to the API menu within the Salesforce set up screens, and then it’s dynamically generated, so it’s not just saved there, it’s as soonas you click it and want to view it, it’ll actually generate the latest version of that. So I can see the Enterprise and Partner WSDL, save that locally and consume it.

Demo Description: Accessing Force.com WSDLs

So in this demonstration we’re going to do something simple, but I want to make sure that we actually look at this web service definition and see how to access it. We’re going to log into our Force account, we’re going to navigate to the WSDL view. We’re going to go ahead and save that Enterprise WSDL to our machines, and then finally we’re going to inspect the Enterprise WSDL and take a look at it, see what’s in there, and be able to access it and look at some of the key things in there.

Demo: Accessing Force.com WSDLs

We are back here in our Salesforce account. Make sure from module 1 that you went ahead and created an account and logged in and created all your objects. So where we can do is go to our various setup screens and this will give us control over looking at where these WSDLs are, so we click on the Setup Home, and we can search for it or you can go down to Custom Code and you’ll find API under here.And from here you’re able to see the Enterprise and Partner WSDL. Now it’s probably user error on my part or they’re still working through some things on lightning; I haven’t had as much luck accessing this from this interface, so what you can actually do is if you can click here, fantastic. What I’m going to do is go ahead and switch to Salesforce Classic and that lets me go back to the classic Salesforce interface that’s not all lightninged up. So here I can go back to the classic, go back to Setup, and then it’s easy enough to also locate the API by going to the Develop menu under Build and click on API. And I can see the same sort of screen, Partner WSDL, Enterprise WSDL. For comparison purposes, this is the Partner WSDL and this one, as you can see, just has a root s object and that’s really where everything goes. You’re not going to see a lot of things underneath here that are specific records type. Instead you’re just going to see some operational values, enumerations, things like that, a lot of the operations, but not a lot of definitions. I’m going to go back and if we go to the Enterprise WSDL, what you’ll see here is something a little more descriptive. So you have things like account, it’s actually the type account that has its objects in it. I should expect to see the things that we created when we created things around voters and such. So all of these things have very strongly typed, all the field types, it represents a lot of the different field types, we’ll talk about that in a few moments. But as we go all the way through I can see things like Voter_Donation__c, so here’s my custom object, it extends the base sObject, but there’s my custom fields, all that sort of thing. So the Enterprise WSDL, and you can save this to you machine if you wanted to and then run this against your Java tools or .NET tools or other tools to generate stubs that then know about these objects, know about these different field names. The Enterprise WSDL is going to give you the best experience for being able to deal with strongly typed objects. But you may choose to like the flexibility of the Partner WSDL, either way what you would do is go to that location, click this output, this is dynamically generated so if I made a change today, right now, to this donation object and went back here and regenerated I would see that new field or different data type or whatever I had done different to it, that makes it really nice and convenient. It’s not a one-time hit, I can change this whenever I would like.

What Are SOAP Objects?

So we just saw an example of the web service definition that talks about some of the s objects and talks about what these things are. Let’s dig in a little more and understand what are SOAP objects. We’ll go through a couple of things here, talk about them in different data types and the like. So I want you to have a strong sense of the objects you’re dealing with. So objects represent database tables in essence. That’s really what you’re talking about here. And as we’re building s objects, just think of them as that. When I built a Voter object, I built a Voter table in the system really. I mean Salesforce is this sort of database driven application platform and so these objects really represent tables underneath the covers. Also note that many of these things I’m talking about here apply to all the objects in Salesforce, not just SOAP. So the things you’re learning here are going to apply very nicely to things like REST and Bulk and others. These object concepts are fairly similar. So as you think about records in an object, they’re really like database rows. When I get records back for a voter donation, it’s like getting back rows in a database. So again, that’s how you should be mapping this sort of concept. There’s multiple types of objects, there’s standard objects, custom objects, and external objects. So standard objects are the ones that are provided out of the box by Salesforce and almost all of those are read/write through the API, you can mess with them in many cases.There’s a few that are read-only, but for the most part this is providing you full access to built in objects that Salesforce seeds your account with. Custom objects are different, we’ll talk about that in a moment, and external objects. So let’s talk specifically about those object types. So Standard objects are built in, they’re already created for you by Salesforce, and they’re called Standard objects. Custom objects are those you’ve created within your organization, think of those as custom database tables that let you store whatever data makes sense and is unique to your particular organization. Now you already know this, maybe, that as you name a Custom object, by default Salesforce adds an __c suffix. It also gives you the same audit fields that it puts on the Standard object, so things like created by,last modified date, et cetera. So those objects are still first class citizens in the platform, but still add the same things; they’re obviously part of the things like the WSDL definition. So you really do get some great experience by building your own objects, and frankly that’s the power of platforms like Salesforce where you’re not locked into an object model, it’s very, very easy to extend that. The final type is External objects. We won’t be dealing with these much in the course, but these are ones you create that map to data that actually sits outside your org. So they’re very much like Custom objects, but that data that goes with a Custom or an External object, rather, it’s stored outside the org so it might have data that is typically associated with your online ERP system and instead of copying that data in and loading it through a bulk job or SOAP endpoint, those External objects can access that data in real time via a web service callout. So we’re not going to be using those here, but they are a pretty powerful way to dip into external systems when you want to look at that data and make it behave like a built in set of data. So let’s talk about the data types, a few key things to remember here. There are primitive data types, things like Base64 for binary or Boolean or dates or datetime, by double if you have decimal values, integers, strings, and time. So very basic primitive types, but these are, as you can imagine, form the foundation for a lot of your objects. Is a name a string? Yeah I hope so in many cases. Am I doing things, like I’m storing a number, if it’s a donation it’s probably a double or a decimal. I’m not going to do an integer because it could be fractional. You know, a lot of those things you want to think about. It’s very easy to kind of mail it in and just make everything a string, but you’re sacrificing functionality by not being able to do things like date comparisons or other logic checks. So fight the urge to just say string, string, string, make everything text and not worry about it, really think sometimes, but don’t over think it because you also don’t want to lock yourself into a data type that’s inflexible for some future use. In addition there were field types. These are types of fields, things like address, which is a compound field, which we’ll talk about in a second. Things like calculated fields or combo boxes, pick lists where I want to be able to choose something from a list. They could be currency, email where it uses a mask to make sure you’re entering in a valid value. You can use encrypted strings or ID fields, even location with longitude, latitude, percent, phone number,and even like references, almost like a foreign key field or URLs. So you have a lot of different types of field types that you can associate with a field that gives you more control over that user experience and runtime validation. Finally there’s compound fields. These are grouped together of multiple elements, like primitive data types and others, so imagine things like a location, which is actually made up of multiple things like a longitude latitude or an address made up of a street address and a city and a postal code and things like that. The idea behind compound fields is that it’s a little more understandable, here’s just a set of fields that represent one thing. The compound field itself is read-only. The changes get performed by writing to all the individual component fields, so I’m not writing to the address, I’m writing to the billing street or billing city or things like that. If we talk about the field details, things like system fields, these are read-only fields found on pretty much every object. They’re automatically updated when you make API calls, you can’t change these, things likecreated by ID, well the system sets that and says your ID created this object, or the created date, last modified date, things like that. These are system fields. You can see them, you can read them, but they’re not editable. One more interesting thing on system fields is that when you do import data and want to retain some of the audit values from that source system, you can actually set the value for audit fields on some objects, not every object, custom objects, some built in standard objects like account and event and contract and others, so you can’t set the timestamp, but you can set things like last modified and things like that. So when you do do an import, you can actually do some settings that allow you to set those system fields on the initial import so that you retain that audit data from the original source system, which is pretty cool. Required fields I hope are fairly self explanatory. They are required. They must have a non-null value, they must be filled in. So this affects any create or update calls. If it’s a required field and I’m creating it through the API, it must exist. One caveat there is if that field has a default value, then I don’t need to pass it in. The political part may be required on a voter, but if I defaulted to an independent and I don’t provide that when I create something, then it’s fine technically, it’ll go ahead and just automatically set that.It’s still required, but my client application doesn’t have to explicitly set it. Finally, a lot of fields have properties and so the details of that particular object and, you know, a field is really like a column in that database table, they can have properties like is it auto number? Does it auto increment? What should the default value be when I create it? Can it be null or empty or not? Can it be queried? Can it be retrieved? So things like that, often accessible and visible through the API when you’re setting or retrieving those sort of field or column level values. Let’s talk about relationships. This is not that kind of video, but relationships in SOAP objects. Specifically there’s things like master-detail. This is a sort of parent child relationship where that master object controls some of the behavior of the detail object. So I could have a voter map to a donation that they made. If I delete the voter, I want that donation to go away too because with master-detailwhen the master object is deleted, its related detail records are also deleted. So it’s important to know this is a very strong relationship between objects that I want to make sure when I’m choosing this that I want that sort of tight relationship. You can form a many-to-many relationship using two objects, this isn’t a default type within Salesforce. But I can create this by creating a junction object, if you will, if you’ve done this with databases before and tables, you really create a junction object and then kind of join it to each end of it, so let’s go ahead and create a junction object that connects a voter to precincts and multiple precincts. I don’t want to tightly couple them with master-detail, maybe I create this junction object so that a voter could be part of multiple precincts and the precinct could have multiple voters. I could choose to do that using this sort of junction object with master-detail relationships on each side of it. Finally, the last built in type of relationship is called a lookup. this links two objects together, but doesn’t have any effect on deletion or security or things like that.So it’s not automatically required. I believe we did this in one of our custom objects and we’ll see this more as we mess with it, but this, again, gives you a less tight relationship between the two things, both sides are able to evolve independently without deleting or changing each other.

Types of SOAP API Calls

Let’s talk about the type of SOAP API calls. There’s a few ones to be aware of that you’re going to want to be ready for. There’s core calls. These are things that you would expect. These are things like dealing with s objects really, create, delete, get deleted, where you can pull everything that’s been deleted from a preset time, get all the updated things, invalidate the sessions, log in, log out, merge records, query records, query all the records, which include things like that have been deleted, retrieve things based on an individual ID, search, update, _____. We’ll use a number of these throughout the course; these are really the core calls against s objects and to some extent your account. What’s pretty cool is there’s a lot of describe calls as well, things like describe all the tabs, describe the app menu, describe all the quick actions available, describe global, all the objects in my org or describe the layout, which gives me all the page layouts for a particular object, describe an s object. So these are things that are almost metadata driven, they’re telling me about that user’s experience, they’re telling me about my org, they’re telling me about my objects. And this can be really useful when I want to be more dynamic with my consumption and I don’t want to presuppose what the setup or my objects are. And then finally there’s utility calls. These are things the API or your client can call to obtain system timestamps, user information, change user passwords, send emails, all those sorts of things. These are kind of just general purpose calls that help you do some things within your account itself. Some of these describing utility calls are unique to the SOAP interface so don’t expect to find this in the REST one as well.

Demo Description: Making SOAP API Calls

Alright let’s jump in and do another demo. So we’re going to go ahead and create a new SOAP request in Postman or whatever tool you would like to use to make HTTP requests. We’ll go ahead and generate that session ID. We’ll query the voter records that we’ve created and we’re going to go ahead and also do one of these sort of utility calls and retrieve the Force.com system level or server timestamp.

Demo: Making SOAP API Calls

Here I am in Postman doing some requests against our Salesforce API. What I would like you to do is we’re going to create a new request, if you had saved these from module 1 you already have one around SOAP Login, if you don’t then in the mod2 folder that came with the course, you’re going to go ahead and see a SOAP login. What you’ll want to do is take that content and paste it in to your Postman request. This is a post to login.salesforce.com/services/Soap/c and a version, 35 is the version I’m using. Paste that in, replace it with your username, your password plus token, so that should be the combination of those two values. Then you’re going to have a header, it’s going to automatically do text/HTML here in Postman as I go ahead and set this to text/XML, so it’ll do that for me. And then you’re going to add an empty SOAP header that just has a couple of single quotes. Once you do that, and you’ll see the body itself, it’s made up a login object, this is in a SOAP envelope, it’s all wrapped up, typical SOAP style with namespaces and all those sort of fun things. When I send that I get back a 200 OK indicating that it was a received okay, and as you can see, we get a nice response back and I can in Postman do things like look at the raw response or things like that, but what I’m getting back here is I’m seeing here is my server URL, yours may be different than mine, so pay attention to those first few numbers, and then I’m getting a unique session ID that is good for 120 minutes or however long I continue to use it. So I get a lot of details back about my account, what things are allowed, what’s my default currency, what’s my organization name that I might have set there, my role ID, which user am I right now, what time zone am I in. Also sorts of those fun things. So what I want you to do next is create a new tab and let’s go ahead and save this URL because we’re going to want to use it again, I’ll copy that, create a new tab here in Postman, paste that in, let’s make this a Post, let’s go ahead and we’ll set the body to be XML before we put anything in there, and since I always forget the headers let’s just go ahead and do that first. Set the SOAPAction to a pair of single quotes and now let’s do the fun stuff. So what we want to do is we want to query our voters. So let’s go to the file folder that has all your code here and you should see one called soapqueryvoter. Open that up, save everything, go back to Postman, past that in. So what I need to do is I need to replace this TOKEN value and I’m going to replace that with this sessionId, so go ahead and copy the entire result of the sessionId, put that into the TOKEN value, and of course now that I’m thinking about it, I don’t want to log in again, I’ve already done that, so the URL is actually our serverUrl. So let’s copy this, I don’t need to the stuff at the end. I’m going to copy that value, and that is our URL. So whatever yours is going to be, it probably isn’t na30, maybe it is if you just created this. So you’re going to want to have that address, you’re going to want to have the headers, change the sessionId and now we’re going to select the Id and the Name from Voter__c. If we look at the result we get a little header at the top and we’ll talk about headers in a little bit, we get back a query response, we did a query request remember, and we get back Leslie Knope, here’s her ID. So one record came back, so pretty neat. So we were able to do a request of our custom object based on what we wanted. Now let’s say we also wanted the precinct name, and I think it was called Precinct__c because remember it’s a custom field name. If I do another request and I go back and look, sure enough the precinct comes back. Now what it’s coming back with, remember this was a lookup, so it’s giving me the unique ID that came back. Now maybe you can convert that in your head to a precinct name, them I’m impressed with you, I can’t do that. So let’s say I wanted to actually pull back the friendly name. Well also as part of these fields in relationships I can refer to the relationship name, __r refers to that relationship to the other object, and let’s say I want to pull the name of the precinct then. So here I’m saying for this sub-object called Precinct associated with the relationship, give me the name. So here I could see, look it’s going to pull in the Precinct__r and its name is 3rd District. So a nice way to mess with these requests and be able to get back data, get back data from sub-related elements, and pull all that sort of thing back. For the final piece I wanted to go ahead and actually get the system timestamp. We talked about that. How do we do a utility call? So within this SOAP body, this is where we want to change things, I’m going to go ahead and first off save this request because it’s going to be handy to save this in the future, so I’m going to save this in my Pluralsight folder and call this SOAP Query Voters, add that to the collection, now I can call that any time I want. But let’s go ahead and while I have that all saved, I’m going to delete the query body and what I want to do is now add the body necessary to get the server timestamp. Do this is simply urn:getServerTimestamp and capitalization and things can matter, so go ahead and enclose that. It doesn’t need any parameters. If I click Send on that, sure enough I get the timestamp of the server at this particular time. So I’m able to get that back. So I’m showing different types of calls. That was a kind of utility call, I’m not querying a specific object, and I’m able to do those things by messing around with the SOAP payload itself and the sort of types of requests I want to do here.

Handling Faults

Let’s talk about faults. Faults happen. Errors happen, it’s okay. We want to make sure we know how to handle those though. So when you get faults back from Salesforce, from the SOAP API, you get back a fault element with an exception code, so you get back an actual element in the SOAP payload, you’re not getting back an HTTP error, you’re actually getting back a fault within the message itself. So if there might be a query fault, a login fault if I’m trying to login, an invalid object fault if I’m trying to describe or interact with an object that doesn’t exist, a malformed query fault, invalid field fault, unexpected error fault. Those area all specific tight elements that come back in the payload. So they’re actual XML elements that have content that describe the fault. They contain an exception code that’s also described in that WSDL, so the WSDL itself describes a lot of the fault information, whether it’s a duplicate value or you exceeded the ID limit or exceeded the maximum size of the request or have insufficient access, an invalid filter value if you’re doing a query or an invalidlogin, so you get kind of a secondary value that comes back, I get back a false string and fault code and then within that fault type it’s going to be a fault element, like a login fault with an exception code that might say invalid login. So I get some details as well as a message that says what happened, is it invalid password, things like that. So I get some good details from the fault element. There’s also an error with a status code. So when I’m dealing with failures on things like creating, merging, processing, updating, deleting records, I’m actually going to get back and error with a status code, so that gives me a message and some fields of where it went wrong. If I’m trying to create a record I might get back a create response and the result has the error object that might say, hey for this field, like maybe I forgot to add the precinct when I created the voter record and the precinct is required, so it will tell me, required field missing and it names the field. So it gives me some good details when I actually have that error down at the lower level. What’s key though is that the resolution of this is handled client side, so the best you’re going to have to be able to do is catch it, process the error, and you know all the different error types, it’s communicated to you in the WSDL, and then retry if you can, if it’s something that can be retried, or you’ll have to fix the request and resend it. So if you’re missing a required field it won’t help you to keep retrying it, you need to actually add the required field and make that call. So it’s up to you at the client side to handle the errors, it’s just telling you, Salesforce is just telling you that something went wrong.

SOAP Headers

Let’s talk about SOAP headers. So you can include these or exclude these. The API provides you the SOAP headers to client applications. All of these are available in both the Enterprise or Partner WSDL. So they’re part of the request and you can control different aspects, you’re going to find them in both WSDLs, you can actually both find them in the request and response in some cases and some of theseheaders are like all or nothing header, this specifies whether a call can rollback or should rollback changes if all records aren’t processed successfully, so you can decide to make an atomic sort of request. You can get back a limit info header back from calls that shows you information about your organization, like how many API calls have you made. You may have noticed that in the calls we just did. There’s locale options where you can define some of the language labels returned or a most recently used header that indicates whether you should update the list of most recently used items, or query options that let you specify the batch size for query results and even that session header that we’ve seen multiple times, we pass that in as we specify the session Id that we should be using for our request. So these headers aren’t HTTP headers, they’re SOAP headers, but they help us have a little more fine grain control over the interactions.

Demo Description: Working with SOAP Headers

Here we’re going to do a little quick demo, but I wanted to show you some of these headers in action, so we’re going to look at that SessionHeader, we’re actually going to make an API call with that most recently used item header and then we’re going to create a record and we’re going to see whether it gets added or not. So we have control over that based just on the header.

Demo: Working with SOAP Headers

I am back in Postman and what we want to do is create a request and we want to insert a new record and we want to go ahead and see if we can control that most recently used header. So if we see where that is in Salesforce real quick, if you’re in your Salesforce account one place that you can see this information is you see Recent Records at the bottom, you can View All, and this shows you the most recently used item. So the question is, every time by default when I create a new record it shows up in this list. But maybe I want to control that experience and I don’t want things to automatically show up there. So here from within Postman, what I want you to do is create a new request, if you’ve done a SOAP login and you have your results still, you’ll want to use the address that comes back from the serverUrl. So you’ll want to do a new Post request to that URL and, as you remember, we’re going to want to go ahead and make this an XML message, it’s raw, text XML, we’re going to go add another SOAP action header, and we’ll have everything we need there. Now where are we going to get the body from, well I’m not going to leave you hanging, let’s go back to our folder where our code is, and within here what you’re going to see is there’s a soapinsertvoter file. Let’s go ahead and copy all of this, put this into the body of the Postman message, and what I want to do is also steal the sessionId because I’m going to need this to actually make the call. Let’s save that, go back to the request, put that into the TOKEN, and here’s the first header, so here’s what we talked about. There’s a sessionHeader, and here’s a header that’s coming in here and I can see that, that it has a value called sessionId, I’m passing that in. I’ve also added MruHeader, and this is case sensitive, if you happen to spell this with a lowercase m, nothing will happen, I neither confirm nor deny that I wasted 20 minutes remembering that that was the case. So you’ll see I have a field called updateMru, I’ve set this to false. So let’s set this to true, that’s the default value as that’s going to automatically update the most recently used items. You can see, what I’m doing here is I have a voter object, I’m doing a create, we haven’t done this yet. Here’s an s object, and I’m doing this of type Voter__c, it’s got Name Joan, Precinct, the precinct she’s in, I’m going to have to want to grab the real value from this before we make this call and here’s her mailing address. So let’s go back to Salesforce and what I want to do is I want to find the valid precinct ID because I would virtually guarantee the ID that I set in there is not still valid. So we want to Precinct, and where do we get the ID? Well if I view the 3rd District, this part of the value is its ID. So I’m going to go ahead and save that, come back into Postman, and I’m going to replace the value with that. I want her to be part of that precinct. So let’s go ahead now and send this. You can see I got a createResponse and the result id success is true. Now if I left the precinct out or others I would have gotten an error back and you can experiment with that and you would have seen the create response would have come back with an error and things like that or if I hadn’t included the SOAP header I would have gotten a login error. So you can see some of that experience yourself as you mess around with these payloads. I definitely encourage you to do that. If I go back into Salesforce and I go back to the Home page, under recent records, sure enough there’s Joan, I can see her here. She should be part of the 3rd District automatically and this is actually a linked object because we referenced the right field. So Joan indeed did make it. Now I want to delete here because we’re going to go create her again, so she shouldn’t be too harmed by this. Let’s go ahead and pick Joan over here and delete here. So she’s gone, moment of silence. Let’s go back to here and now let’s do updateMru is false. So now I want to still create it, it’s still going to show up, and I still got success, everything was fine, but if I come back to the Home and I look at that little thing at the bottom, it’s not there. Right, I click View All just to be sure, Joan does not exist here. Now if I go to the actual voter records and I jump in Sales and I jump back to Voters, I expect that she will still be here in the, make sure you switch to All list, and there she is. So Joan still made it up, but because we added that MruHeader she just didn’t show up there, and that could be her a lot of reasons, maybe I’m doing a bulk import of records through SOAP and I don’t want to just pollute that feed with a lot of information. All sorts of reasons I might not want to do that. We saw that we had full control over that by setting that MruHeader.

Building Custom SOAP Services

It’s okay to realize that sometimes it’s not enough to use the built in services. You may look at that set of standard and custom objects and the set of services and say, boy it just doesn’t do exactly what I want. I have some business logic I want to do or I want to return these objects with a different shape or I want to mash them up in a way that makes sense for me. That’s okay, and what’s really cool and powerful within Salesforce is that you can define classes and expose those as SOAP services so that I can come in to my particular object in my environment and I can go ahead and make a call to a custom service, when I make that Post request it’s going to a different URL, the class name I create goes in the URL, but it’s still a SOAP request. What I do is I define a global class as a SOAP service. So first of all I define, it has to be global for me to work with this, and then I’m defining a webService keyword, this goes on the operation not the class. Any of these methods I use for a webService have to be defined as static and you’ll see that, I’ve got my webservice static Voter__c, I’m returning a Voter__c object and a method called getVoter, and I can take in all sorts of types, which is pretty cool. So I can send in all sorts of different data types, it works with most, and so I’m able to pass in, in this case, a voter Id. What I’m going to do is a statement and this runs in the system context so be very careful here, in this case I do not care what your user permissions are, your role based access, none of that applies here. So be careful with things like this because you could accidentally leak data that someone shouldn’t have access to. So in this case what I’m doing is I’m making a call into Salesforce saying select the voters where the voterId matches what was passed in, and this runs in the system context, so I don’t care if you don’t have access to voter info, you would still get this result back. What’s pretty neat is you can generate a WSDL from this. So once you’ve built this class, you can generate a WSDL, consume this just like you would any other Salesforce service, and interact with it. So this gives you a ton of control for being able to build services that meet your organizational need, whether it’s custom algorithms, whether it’s other logic, or simply the way you want to retrieve data in a different shape, you’re able to do that. So very neat stuff. Now if you wanted to, if that system context thing worries you, you could also do some things like within this operation, call something like describe s object result or describe field result, to check the user access inside the operation. So there are ways you could add some checks within this to make sure that the caller has the permissions to do what they want, but do not assume it’s by default.

Demo Description: Creating a Custom SOAP Service

So in this next demo what we’re going to do is we’re going to go ahead and create an Apex class, and no worries, I’m going to give you the code for it so it’s not too complicated. We’ll add the code the retrieve the user ID or the voter ID, we’ll decorate that with that webservice keyword, we’ll call that service from Postman and see that I’m able to make these calls and get back data even from a custom service.

Demo: Creating a Custom SOAP Service

I’m here in the Salesforce, my account at least, and what I’m going to be doing here with you is going ahead and creating a new custom apex class, calling that from my outside application. So let’s go ahead and go back to our settings experience, go to the Setup Home and from here I have a few ways I can do this, I can either search for Apex classes, that’s fine, or just so you know where it actually is you’ll find this under Custom Code, Apex Classes, so let’s pick that. And I have no custom Apex Classes here in the moment, that’s fine. I can click New and I’m going to get a new window where I can actually type in the details of my class. So instead of having you type this in, go back to the folder that has the code in it, in this mod2 folder what you’re going to see is a soapvoterservice one here, go ahead and copy all of that, come back and paste that in. So what you’ll have here is a full class, so as you see it’s a global class, we’ve decorated it with thewebService keyword, it’s static, gives me back a Voter object. The operation itself is called getVoter and it takes in a string of the voterId, then I go ahead and populate that Voter object based on a query and return that object taking in that variable that comes in here. So I can click Save and now this is something that I can invoke. Now I can click Generate WSDL and I could go ahead and actually get a web service definition related to that that I could consume in my application code, which is great, so this has everything I need to make the call, it’s a big fat WSDL because it has all kinds of other stuff in it as well. In our case, what I’m going to be able to do is simply go right to Postman and paste in some content here. So within Postman, let’s go ahead and create a new request, it’ll also be to a Post. I’m going to go ahead and steal part of this URL, so you can steal the last one you did from the last exercise. I can go ahead and paste that, but the difference is going to be instead of the normal URL it’s going to be SOAP, then it’s going to be class and then it’s going to be Soapvoterservice, this is the name of the class. If you called your class something different, then it would be that. In this case, this is the content here. It’s going to be text XML, you’re experts at this by now, go into your SOAP headers, let’s add a SOAP header. This is SOAPAction, a pair of single quotes, and then where are we going to get the body for this thing? So let’s go ahead and go back to your folder and you’ll have soapquerycustomservice, I’m going to copy this, all content, I’m going to paste that into here, and as you canimagine, we’ve got to steal some values, so either from your last request or from your actual SOAP login query, you want to grab the session ID, I’m going to steam mine from my last query, do whatever makes you comfortable. Let’s go ahead and put that in there, and then most importantly I want to put a valid voterId in here, this is not one, at least not for your accounts. Let’s go back to Salesforce and I want to find one of my voters, so I’ll go back to my app launcher, I’ll pick the Sales app and we want to jump down to Voters and I want topick one of the voters, so let’s pick Joan. I can get her ID by viewing her record and then grabbing this value at that point in the URL. I want to paste that in here and that’s her ID, so again, look at this request, I have the header, the session header, I’ve got getVoter is my element, my payload, I’m passing in the required voterId, right, that’s the parameter that are service dictated. This is whatever my custom web service says it’s going to take in, then it’s going to query the database based on this value and hopefully return me back something. I made my call, sure enough what came back Joan Callamezzo, I’m great, it actually queried my custom service and I get back the Id and the Name because that’s what I put in the object. So pretty neat that I’m able to make this call to a custom service, very easily invoke it into a different URL. The payload is going to be specific to whatever I dictated my service, but a pretty neat way to build my own service that matches my business need.

API Limits

So there’s no exactly free lunch when I’m dealing with APIs, there are some constraints, some sandbox just a little bit to make sure one company doesn’t take advantage of the whole platform. This is a multitenant public cloud. So Salesforce puts some boundaries on you to make sure that you’re not going completely nuts. Things like you can have 10 concurrent queries per user, so you can have 10 query cursors open at the same time, so multiple client apps can log in with the same username, but then it increases the chance of bumping into this, so as you build client apps, you might want to have them logging in with their own users because otherwise you’re going to quickly bump up to this limit You can have 25 concurrent calls in a production org of 20 seconds or longer, so 5 in a dev edition, 25 in aproduction and sandbox account. So you want to make sure, again, you’re thinking about this of how many concurrent calls might I have. You can do a million daily API calls in a production organization, at least for an enterprise account, it’s less for a dev edition. So depending on your licensing, these things can change, check this out in the documentation, but be aware of these limits, and then finally, 200 maximum records in a create or update request, keeping that in mind and even a 50 MB maximum request size, again, you can’t just dump in thousands of records with an API call, you’d want to think about which API to use if you were dealing with that volume of record.

Monitoring API Usage

Finally I want to talk about monitoring API usage. What are we thinking about when we’re trying to figure out how much have I used? Am I close to those limits? Who’s doing what? And so you have three different things you can do. I can view the request for the last 24 hours and see what’s going on there, so I can see what’s happening in my account over the last 24 hours. I can look at an API usage report and see some information there, it’s a little trickier to access so I’ll show you a secret way to get into that report. And then finally you can even set up API usage notifications. This will actually send you an alert, it’ll let you know if you’ve hit certain limits or if you’re getting close to your limit so that you can either throttle back your access or at least be prepared for the fact that some of your users may get shut out.

Demo Description: Monitoring API Usage

In this upcoming exercise, this last one of the module, we’re going to look at the 24 hours of API calls, we’re going to run a SOAP API call report to see how many calls and who’s been doing it, and then we’ll go ahead and look at how you create usage notifications, so give you a sense of how you would keep track of what’s going on in your account.

Demo: Monitoring API Usage

In this exercise let’s take a look at how do I monitor some usage, how do I see what’s going on with my account? So one easy way is if you look at your setup screen and we jump to our System Overview, you can find that under Environments and go to System Overview, you’ll get a nice little recap. I have 8 calls in the last 24 hours, hey that’s with you all. So I can see really easily here how many custom objects do I have, how much data have I stored, how close am I to my limit, how many business rules do I have? All those sorts of things. How many custom tabs? Great stuff. So I can see, but really easily, how many API calls have I made. Another way, kind of a secret way, is I can’t seem to get this going in Lightning, so I’m going to go ahead and switch my account back to Classic for a moment and then I’m going to go ahead and paste in a URL that is my server, so make sure you plug in your value, get the 00O?rt=104 and when you plug that in you actually get the API calls made within the last 7 days. So I can see on Saturday I made 5, Sunday I’ve made 8, so obviously the 24 hours is about 8, which company, which email, which user Id, all that kind of stuff. So I get some decent little data here, I can see some information by user or by things like that, the call count, so not a ton of stuff, but at least I can start to see who’s doing it, right, I can see who’s getting me close to my limits. That’s kind of a secret report that I haven’t found a way to view within the experience within Lightning. Let me switch back to Lightning. And then the last option is if I go ahead back to Setup, what I want to do is look at the API usage notifications. So if I go ahead and do a search for API, you can see under Monitoring, there’s API Usage Notifications. What you can do here is create a brand new one and say what I want to do is who’s the recipient, this would have to be someone within your account, so me at this point or you, what’s the threshold, let’s say 85%, 24%, whatever you want to say, what’s the notification interval, right, how often, things like that, once per that number of hours. I might not want this all the time or maybe I want this every hour just in case. So I can at least get a notification to that person when I’ve exceeded my threshold. So it’s not super crazy, it’s not, you know, tons of options, but it is a nice little way to get myself a push notification when I’m getting close to my limit.

Summary

We’ve reached the end of the module, I hope you had fun in this one. We did a lot of stuff. We talked about obviously the goals for the whole module, we jumped into the anatomy of an individual SOAP call, looking at things like the headers and looking at how you post to it, where you store the credentials, all those sort of things, so we understand what a SOAP message really looks like. We talked about authenticating users with that short lived session ID. We talked about both the Enterprise and the Partner WSDL and even saw an example of the Enterprise WSDL and how it had strong typed objects in there. We looked at all the different types of SOAP objects and field typesand data types, core calls, different action types, and tried to look at the differences between those so you’re aware of the breadth of the SOAP portfolio. We looked at handling exceptions and hopefully you experiment a little bit with this with the calls that you now have saved up in your tool and go ahead and pass in invalid credentials, go ahead and request values that don’t exist or s objects that don’t exist. You can see how those exceptions are returned and how your code is going to be responsible for responding to it. We talked about SOAP headers and saw an example of messing around with the most recently used header. We built a brand new custom service and we took that custom SOAP service and then called it and saw how we had some control over what we got back and how we interacted with it. We discussed API limits and being careful about how many calls you make concurrently, how many calls you might make per hour, even how much data you pass in for an individual request. And then finally we talked about monitoring usage. How do we make sure that we’re using the right amount of data or that we’re not over exceeding our available API calls? So being able to look at those reports is important.Hope you enjoyed this one, the next one up we’ll look at the REST API, which has some similarities to SOAP, of course, but a number of different ways specifically around authentication and interaction pattern, where it’s a web service call, but in many cases the entire interaction pattern is different while the payloads look very similar.

Creating Lightweight Integrations with the Force.com REST API

Introduction

Hey there, my name is Richard Seroter. Welcome to this next module in a course on the Salesforce Integration APIs. In this one we’re going to spend some time looking at connecting to Force.com through the REST API. In the last module we checked out the SOAP API and how to use it and also did a little more setting up our account. Specifically we’re going to take a quick look at the anatomy of a typical REST call, kind of standardize ourselves with how REST works. We’re going to discuss authenticating users; this is very different from the SOAP API so we’ll take a look at that. I’ll explain some of the REST objects and actions and how you interact with the REST endpoint. We’ll talk about the role of HTTP response codes as this plays a different role than the way errors were sent in a SOAP payload, now you’re actually dealing more with typical HTTP communication, so you want to understand what those response codes mean. We’ll talk about conditional requests and how you can do some interesting things with caching. I’ll look at composite calls, there’s a really cool capability with theREST API where you can do these sort of grouped operations of different record types or related records, nested records, and we’ll see how you can take advantage of that, much like with the SOAP service I’ll show you how to build a custom REST service. This is great when you want to do something that isn’t provided by an out of the box service. And then finally, we’ll summarize. Like before, let’s have a simple definition. The REST API is simple access to Salesforce data and functionality via RESTful endpoint. Again, REST is something where there’s enough religious debate over SOAP versus REST and is something actually RESTful, the point is is trying to use resource definitions and HTTP verbs in a stateless fashion in order to communicate with a system.

Anatomy of a REST API Call

So when we look at a typical REST message it has a few components. You have HTTP verbs, unlike SOAP that uses one single overloaded HTTP verb. With REST the verb actually has meaning, so whether I use POST, like in this example, to create something, I would use GET when I want to retrieve data for a resource. I’d want to use PUT when I’m putting a resource in a specific resource ID, and I might use DELETE when I want to delete that resource. The resource you care about gets identified in the URI. So instead of well we just kept hitting the same endpoint over and over again for SOAP services and the payload determined what to do with it. In this case, the resource itself, Voter in this screen, is showing you that’s the resource we care about. Security is extremely different than with the SOAP service where you were just using a username/password combo. Instead OAuth is taken advantage of with the REST service and we’ll go into that in depth. And what’s great is you can use JSON or XML payloads. This is where some of the simplicity comes in with a RESTful service.

When Do You Use It?

So when do you use this? Well three cases I’ll call out. Integrating with mobile apps. This works well from an identity perspective where it’s very easy to have different authentication schemes that don’t require you to know the user’s credentials ahead of time or cache those on your application. It’s also more lightweight because I can use JSON and I’m not getting all of these XML wrappers and so I’m going to have at least a smaller payload, and it’s easier for things like caching and other things where high performance comes into play. It comes in when I want those lightweight JSON interactions. Most modern, very newer systems don’t really like taking advantage of XML. They’d rather work with JSON and using JavaScript in their app so much instead of having XML and having to then serialize it into a JSON format. Instead when I’m dealing with JavaScript apps, I might as well have the payload in JavaScript format or friendly notation as well. And hypermedia is great, so one of the characteristics of a good RESTful service is that you also have identifiers and kind of followable links to other resources. So I get back one resource and I can also get back links to related ones and I get back the actual URI I can follow to go get that other thing. So it gives me a much more exploratory sort of API and payloads that let me actually kind of navigate various related things.

Authenticating REST API Users

Let’s talk about authentication; it’s a big part of what is different in the REST API. And so Salesforce does use the OAuth protocol to allow users of these different apps to securely access that data without having to give up their username and password. So the key is at first you define a connected app and we’re going to do this together in a moment. To authenticate the OAuth you have to create this connected app that defines your application’s OAuth’s settings for your specific Salesforce org. For OAuth in general the idea is that, and Salesforce does a good job complying with this, you have endpoints for authentication, token request, revoking tokens, but OAuth itself is an open standard for authorization. It’s used often as a way for internet users to log into third party sites using various different sets of credentials within having to give up their password. You see this all the time, login with your Facebook ID, login with your Google ID, and then you’re more or less redirected to that, you have this sort of secure delegate where the app trusts that identity provider, it trusts Google, it trusts Facebook. It knows that when Facebook says this person is who they say they are, they can trust that particular token and proceed, and meanwhile your app doesn’t actually have to have your credentials. I don’t have to actually share it because I have a trusted third party.Much like with the SOAP API though, user, object, field security, all those things still apply. So I still have secure access that respects the access I have in the application itself. So if I’m using the Salesforce user experience, it’s the same thing if I’m using the API. As I mentioned, this OAuth security model. So you are dealing with a standard sort of model, standard sort of identity model where Salesforce is acting like that system of truth and help make sure that your remote apps might not necessarily have to store credentials, they can use one of a number of flows, and we’ll talk about these. These different flows help you address different interaction scenarios. So it’s not one way of dealing with OAuth, instead you have a lot of different models and we’ll focus on three of them here that are very popular. So three popular flows. Let’s look at the first one; this is the Web Server Flow. This is used by apps that are hosted in a secure place. So the server is actually able to protect the consumer’s secret and credentials. So it’s key, I trust that the web server is secure and it can protect this secure information ahead of time. The client app redirects that user to login. The client app never sees the credentials. So in this case you start off with the client application directs the user to Salesforce authorization endpoint. That user then logs into Salesforce with their credentials, they put in their username and password. If that login is successful, you know, obviously you’ve logged in with your correct credentials, there’s a callback URL and that callback URL is passed back with an authorization code. The client app then takes that authorization code, gives is to Salesforce to actually get an access token. So again, in this case the client app doesn’t have to store any credentials, I’m getting the user to log in, I’m getting back a proper authorization code and then the client takes that code, makes sure it’s a real one, and they can get back then an access token, the refresh token, and then get back that instance URL that we’ve been using to say which instance of Salesforce should I target. And then finally the application can use that access token and access that Salesforce data. This is great; this is pretty handy when I want to make sure that I can just kind of route things through this secure web server that can store that consumer token and it gets back and at the same time your client app doesn’t have to store your actual credentials. If we look at the User-agent Authentication Flow, in this case the consumer app isn’t expected to keep anything secret safe, it shouldn’t store anything, it shouldn’t store these sort of tokens. So in this case what I want to do is make sure I’m redirecting the user again, the user logs into the Salesforce page with their credentials, if it’s successful user is routed to that callback URL with an access token. So I don’t even want to give them a secret and then to go get a token, they get back the access token, and then that application goes ahead and access the Salesforce data. So it cuts out the middle man of receiving back an authentication token. Finally, you have the Username-Password Flow. This is one that I definitely recommended you don’t use this for production. You only use this when necessary. This is used when the consumer already knows the user’s credentials and doesn’t have to even ask for them. So the client app request the token using the username and password, Salesforce verifies those credentials and gives you back an access token and the URL, and then finally you use that data to access Salesforce. So in the first case I’m routing the user around, I have some trust in that web server that can keep this interaction safe, I’m getting back an authentication code, I’m confirming that with Salesforce and I’m accessing data. In the user-agent one I cut out that middle man because I’m not trusting my desktop app, my client app, whatever. I’m just authenticating getting back a token and then using it. In this case I’m not even asking the client, I already have credentials I’m using on their behalf. As you can imagine, that’s one you’d want to be very careful with.

Demo Description: Authenticating REST API Users

So let’s do our first demo for the REST API. What we’re going to do is create a connected app, then we’re going to go ahead and view the OAuth settings that we configure for that app. We’re going to use Postman; we’re going to log in to the API with the username and password flow, that one that’s a little less secure, but obviously a lot easier for demo purposes. Then we’ll review those API results and simply see how that flow works.

Demo: Authenticating REST API Users

We’re here in the Salesforce environment that we set up back in the very first module where we set up our account, we added some custom objects, things like that. Now we’re going to go ahead and make this OAuth friendly. So let’s go to the setup screens, click the little gear, pick Setup Home, and what we’re going to do is we’re going to search for app because I want to go ahead and create a new app. So I see Apps here and I want to select Apps here, and I can see my various applications. Now we didn’t create any custom apps here, this is where we could create a new custom app. You see Subtab Apps and then you see something at the very bottom that says Connected Apps. Go ahead and click New here. And now we’re asked to create a Connected App. Let’s go ahead and call this VoterTrax Pluralsight. It automatically gets a name; let’s give it an email address, I don’t feel like giving it a phone, you can give it logos so you have kind of custom log in pages and things like that. So that’s how you start the page. Now if you look you’ll see you can enable OAuth. You don’t have to, in this case, of course, I do. And so you have a callback URL. Now this would be typically your application endpoint, because we’re not going to use callbacks I can just put in localhost here and that’s fine. This would be technically, as you remember those flows, this is where it would route that authenticated user back to with either the authorization code or even the token back in the message. In this case I’m not going to use it so I can say let’s go ahead and do that. Then I select my scope. What is the permission I’m giving to this particular user? So I want to give access to Access and manage your data via the core API. I could give full access, all sorts of different scopes here. I’m going to choose just that one. I’m not going to set anything else up, and I’m going to click Save. I’m going to click continue here, it takes a few minutes for these things to actually commit to servers. So we’ll click Continue and then we should be able to see our application here. And you’ll see these are very, very important values. So if you look at the OAuth, specifically you’re getting the consumer key, it’s a really unique easy to memorize value, and then consumer secret, when you click that it actually shows it to you. This is very private stuff. I’m clearly showing you mine and these values will be different, this app won’t exist when you take the course. But the key is these are values you should not socialize. These are very protected values. So here are your things, so I can see those values and I’ll need to use those.There’s other things you can do with this Connected App, so let’s go ahead and go back to Apps. And if I go to the bottom, I should now see VoterTrax Pluralsight. If I click Manage, I see some additional things with my app. So I have OAuth settings. I can also do things like control my IP restrictions. Should I use the ones built into the environment or should I relax those? So for the sake of fun here, let’s go ahead and edit that, and let’s go ahead and relax IP restrictions. And so again, I can just change a number of things, what should the session timeout policy be, it’s 120 minutes by default. I can do all sorts of different settings, very nice. So I’m going to go ahead and save that. If I want to go back to the OAuth settings, I’ll go back to Apps again, I click on the actual Connected App name and I can see the consumer key and the consumer secret. So let’s go ahead into Postman. From within Postman, now we’re going to go ahead and do a GET. So I just want to do a simple login actually to the right endpoint. So here it’s not giving me any payload, I’m doing a GET. So again, unlike SOAP where you’re doing POST to everything, in this case I’m literally just doing a GET. So I’m going to do https, so I’m going to publish do a GET to https://login.salesforce.com/services/oauth2/token so that’s going to be the first part, very important, but now what really, as you can imagine, matters is going to be the actual payload, and so in this case I have to make sure I add form data headers that have all the different token information that I need. And actually I need to switch this to a POST because I am posting values, I’m actually authenticating, so I have to actually provide data in the payload that authenticates me. So I’m actually posting to get back the token, if you will. So what we do is after POST I’ve got the URL, then I want to go to the body and I want to do form-data because I’m going to send in a number of values here. I’m going to have the grant type, _type, that’s the flow I’m using. Then I’m going to have the client_id. This is the value from Salesforce. So this is going to be the consumer key. Then I’m going to have the client_secret, this also comes from Salesforce.Here I view the consumer secret, pass that in. Then, as you imagine, I have the username, mine was richard-Pluralsight@seroter.com, and of course the password, this being the password plus token value. If you choose to you can go ahead and look at the SOAP login, if you had saved that in Postman, and go pull that value out, unless you already remember that or stored it elsewhere. So I’m going to paste the password in there. Then with all the values in there correctly, go ahead and click Send and what do you think I get back? Well hopefully I get back a valid request. I get back my access token, my instance URL, the token, it’s a Bearer token, when was it issued, and what’s the signature. So it’s great, I’ve proven that we’ve logged in. I did a POST to the OAuth login, I used the username-password flow, which is not ideal in most cases, but we created the Connected App, we passed in the right values in the body, and to make sure we’re going to use this time and time again, go ahead and save that in your Pluralsight collection and this could be REST Login, as we’ll use this over and over again throughout this particular exercise. We’re able to login successfully with OAuth.

What Are REST Objects?

So we just successfully created that consumer app or that Connected App, connected through OAuth. But let’s dig into now actually what are REST objects? What is the REST endpoint? And then we can start invoking some things against that. So if we look at what are REST objects, same data model, same objects as the SOAP API. I can work with standard, I can work with custom objects, same field, same field types, very, very similar to the SOAP API. Obviously the difference is in the wrapper and how I engage it, but the data is very similar. Just like before, records are like database rows, you’re going to get all these sort of things back and you’re going to have the same support for all the same types of objects. So standard, custom, external, all of those still apply when you’re working with REST.

Types of REST API Calls via Standard Interface

When you think of the types of REST API calls via the standard interface, and again, I call it the standard interface because you’re still dealing with HTTP verbs. I don’t have to know unique operation names, the only thing I have to know is the resource. If I know the resource then I can execute the standard interface against it to get it, to create it, to delete it, makes it very, very consistent for how to access. Now Salesforce itself does not break it up these three ways, I’m just using a similar naming scheme that they did for SOAP. So this idea of core calls, getting s object rows, creating and updating records, querying, processing rules and approvals, searching, composite operations, all those things are kind of core calls working with the core objects within Salesforce. The REST API also has, at least conceptually, thesedescribe calls. I can describe an s object. I can describe global, which gives me back all objects. I can get layouts or tabs or themes. So they still have the concept in REST, it’s a smaller surface, but I can still do some description things within the REST API. And then like SOAP, and again, they’re not called this, but there’s sort of hanger on operations, kind of utility calls. Hey get my limits, get or set a user ID,get or set a password. Just kind of basic things that still help you with managing your account. So while again, not called this way, hopefully this helps you just categorize these mentally within the types of calls available.

Switching Between XML and JSON

One of the best parts about the REST API is the simplicity between switching between XML and JSON. So you can append.xml or .json to the URI and you get back then the right representation. This makes it really, really easy where Salesforce itself doesn’t care; it’s just a serialization question. So you’re choosing how do you want this data returned to you. So you can do that first off by just appending to the URI, and this works in most cases, if you’re doing searches and such it doesn’t work this way and that’s where you would want to use the accept header. So if I have something more complex, I could choose to use the accept header and that’s another way to also get back either text XML or text JSON and get that sort of information back. The default is JSON when I’m working with the REST API.

REST API Response Codes

Let’s talk about response codes because Salesforce is good about using the standard HTTP codes when giving you back something. So they’re not inventing error types, instead they’re using what you would expect when you call a REST web service. Hey if I get a 400 back, that’s a bad request in any location. If I call 401, that’s unauthorized, or if I do a 201 that means you just created something for me. A 200 is an okay. So all of these are very standard. So if we go one by one briefly, a 200, the industry response, if you go to the, you know, the standard bodies and say what is a 200, that means the request has succeeded. In Salesforce that means it was successful for either a GET or a HEAD request. That’s fine, that’s what you would expect back from that. For a 201, again, the industry expectation is the request has been fulfilled and resulted in a new resource being created somewhere. In a Salesforce world that means you had success when you did a POST request creating something. 204 is interesting, it means the server has fulfilled the request, but doesn’t need to give you an entity body back. So this is what you would get back from a DELETE requested Salesforce. There’s no content, but lets you know that this still was successful. For a 300 that means whatever you asked for actually corresponds to a number of things. So in Salesforce that might mean the ID you gave me is in more than one record. So I’m going to give you all the matching records. A 304 is not modified. So this would be a conditional scenario where you did a conditional GET, you’re allowed to do it, and the document has been modified. So in the Salesforce world, this means you did this sort of conditional GET and the content hasn’t changed since the last time you asked for, so you’re probably accessing a cached copy. A 400 is a bad request, in the industry that would mean, hey the request, I couldn’t’ understand it because there was some bad syntax. In Salesforce that often means the request isn’t understood, often because your JSON or XML body has an error in it. For 401 in any typical REST service, it means the request requires user authentication. In Salesforce that typically means your session token has expired or is invalid when you get that back, that that’s why you’ve gotten that back, so you should get the refresh token or you have a bad one in the first place. For a 403, in the industry you’re getting that back when the server knows what you asked for, but it’s not going to fulfill it, typically because of permission issues. In Salesforce that means that logged in user doesn’t have the permissions needed, so you don’t have sharing rights or you don’t have access to that field or that object, and so I know what you’re asking for, I’m just not going to give it to you. For a 404, we’re all many familiar with this just in regular HTTP interactions on the web, it simply means that the server hasn’t found anything matching what you asked for. In Salesforce that means you just asked for a record or object that doesn’t exist. And then finally, 500 simply means the server encountered some sort of unexpected condition, which means it couldn’t do its job. In Salesforce, that means I have no idea what happened, but something bad happened, and that’s obviously something that can happen on occasion.

Demo Description: Retrieving Records with the REST API

So let’s do a demo. Let’s jump in. We’re going to go ahead and call the login API, we’ll get back our access token, then we’ll go ahead and retrieve some records for a standard object. Then we’ll flip around and retrieve some records for a custom object. We’ll perform a SOQL query, so this actually lets me show that I can do queries as well pretty easily through the REST API. We’ll switch those results between XML and JSON, and we’ll wrap up this demo. So let’s jump into Salesforce and more specifically let’s go ahead and jump into Postman and mess around.

Demo: Retrieving Records with the REST API

Alright we’ve talked a little bit about REST, now it’s time to actually put this thing through its paces and understand a little more how to use it. So if you were already in Postman, let’s go ahead and do another REST login request, remember this goes to login.salesforce.com/services/oauth2/token. We’re going to pass in all the values, we’re using a password OAuth flow, we’re going to pass in the client ID and secret, username, password, click Send, and then we’ll get back our respective token. So I’m going to go ahead and copy that value, as should you. Let’s save that. And then let’s make a new request. And now we’re going to do a GET. Let’s target our URL. Let’s remember it looked na30 is our server, so I want to go ahead and type in the right address, and so I went to na30, the server that comes back from my account /services/data/version, in this case 35, /subjects/account. So what I want to do is I want to get a list of accounts. Now how do we authenticate? Well I’m going to go to the Headers tab, if you’re using any other tool we simply have to add an authorization header, which is a standard HTTP header. The key is its value is Bearer because it’s a Bearer token, space and then the long value that came back from the login. If I have all that I should be able to click Send, I should have a valid token, I get a describes at the top, so it describes a little bit about the account. And if we want to scroll down just a tad, I can go ahead and see some information, recent items, and I can see I have one account here, Vandelay Industries, coming back. So this is the recentItems list, it’s just giving me information here about the account, it’s showing me the recentItem list. So it’s giving me some basic information about account. Now let’s describe the actual object itself. Let’s do /describe. So again, RESTful, I’m saying give me the resource at the describe endpoint. In this case I get all kinds of stuff, I’m learning all about different fields, so the describe is actually telling me the metadata about the object itself, which is interesting. So again, I can interrogate that. I can also do this with custom objects. So let’s say I say Voter__c. As you can see, this isn’t actually case sensitive and I get two voters back, I get Leslie and I get Joan back, the two that we had created. And you see this is much more lightweight, I’m getting back a very lightweight entity here. So I can see some details, again, you can see hypermedia, right, it’s linking to other URLs. I can follow this URL to learn about the layouts, I can follow this one to describe the voter object, or simply just to get back again what’s going on there myself really, and then I get a recentItems list, here’s with Leslie and with these other ones. So if I want to go ahead and store an individual Id, I can save Leslie’s Id and then if I do voter__c/ the Id, I’m going to get back just Leslie. Right here is Name, CreatedDate, all the sort of system metadata that I want back for the account, Political_Party, Precinct and so forth. So I can be very specific by asking for the individual thing, I can get back just information about voter by sending it without it, and I get back some information there, and I’m good. So a lot of different ways I can interrogate this stuff to learn different things. Now let’s do a query. So this was dealing with straight up resources, right, give me back voter information, give me back account; give me back what have you. What I want to do is let’s do a query. So from /35 I’m going to do whack query? and I want to go ahead and say q, so my query is select, and let’smake sure we’re URLing coded properly, name from Voter__c+where+Precinct__r, remember I want the relationship to the precinct object, Name+=’4thDistrict, and I think we created one called 3rd District, so this shouldn’t return anything. Let’s see. Let’s click Send. Done, no records. Because I don’t have anything with 4th District in there. So let’s go ahead and change this to 3rd District. So I’m going a query here again, and if I do a search here, hey I get back 2 records, I get back Leslie and I get back Joan, down here if I scroll down. So that works, I did a query. I did select+name+from+Voter__c where the precinct name is that, the relationship, and then the name equals to that. So that’s pretty handy. So again, I could have manipulated this query and added not just name, but precinct or other values if I want to, but I can do full SOQL queries in that language through the RESTful interface. Now let’s go ahead and add an accept header. So let’s go to the Headers, that’s the response, let’s go to the headers of the request and add an accept header, it’s a standard HTTP header, and what I want to add here is let’s add text/xml. Alright, let’s add application/xml, click Send. Sure enough, I get the results back as QueryResult with records, here’s Leslie, here’s a record, here’s Joan, totalSize. So I can get it back very, very easily here with that. So very nice. If I want to do the same thing back to the s object, I could do s object/account.xml and I get rid of this header, and I also now get the account object back in XML. So again, I can put this in the URL or I can go ahead and easily put this in the accept header, it might just depend what I want to do there, how I want to tackle that. So two ways to easily switch it from XML back to JSON or switch this back to JSON, which is the default anyway. But I can do that to get JavaScript back. So nice ways to query objects, run an actual SOQL query or even be able to switch between XML and JSON in a pretty straightforward fashion.

Demo Description: REST API Calls From a Node.js Application

We just finished that demo where we were exploring the REST API a bit, we were authenticating then hitting s objects directly, then doing some queries, things like that. So now let’s actually impact our app a little bit. Now it’s time to mess with that VoterTrax application and so what we’re going to do is set our credentials in the sample app. We’re going to review the precinct.js file and some of its code so we can actually pull people back for a given precinct. I want to test the application, and we’ll be good to go. So this will give us a good chance to see more in action of actually integrating Salesforce into an application itself. Let’s jump in there.

Demo: REST API Calls From a Node.js Application

Here we are back in our dev environment. I’m in Visual Studio Code. I had opened from our last exercise our course files here, so I can go ahead and do Open Folder. If you haven’t done this already, you want to open this and open up the VoterTrax application. Then we’re going to be in here, we’ve already done an npm install to get our node modules loaded up. We already tested this app at the very end of the first module, rather, and we were able to see that this thing runs. Now let’s actually add some meat to it. So you want to open up the credentials.json file. This file stores our credentials for my account, so in this case, clearly you’re going to put in whatever makes sense for you (Typing). Now I’m going to plug in my credentials. You might steal these from that last REST call that we did within Postman, that might be the best thing to grab these values, and you want to set all of these and then save the file. So you want to save this, so now it’s going to log in using your credentials. Excellent. So next what I want you to do is I built this application using Express, a framework withinnode that’s kind of an MVC sort of model where you have views and you have controllers, they’re called routes, and things like that. So in this case the routes we’re going to use in our app, so open up the precinct.js. You don’t have to know much about this stuff, but you will see a few things I want to point out. So I’m using the credential file, that’s where I’m sucking in your credentials and being able to use that,when someone makes a GET request to their resource identified, it’s going to log in to that OAuth endpoint in Salesforce, using password, and then I’m going to use your client_id, your secret, your username and password to log in. If I log in successfully, then I’ll get back the URL that comes back from it. I’ll get back your token. And I’m being bad and hard coding the URL. So set this to whatever yours is, right, remember when you call the endpoint you have an na number, so go ahead and set that. Next let’s go ahead and look at the rest of this query, so we did a query similar to this within Postman. So I’m pulling back the Id, name, Political Party, the Precinct name, all of these things where the Precinct name equals, let’s go back to the Precinct name, 4th District, and I believe when we did this ourselves, we just saw this before, I want to do 3rd District here. So that’s our query. I’ve hard coded it here where it’s going to pull back every record that comes back from that. I’m adding a header. Here’s your authorization header with the Bearer and the token that comes back from logging in right up there, and it’s going to go ahead and render the page. It’s going to go ahead and pass that information back and hand back that list of records back to the page where it’s going to render it on the screen. So let’s go ahead and save that, I’m going to Ctrl+S, and I’m going to go to the debug screen here within Visual Studio Code. If you’re not using VSCode, no problem, go into your command prompt and go into your folder, you know, have node and you’ll start it up pointing to the bin www folder, in this case I don’t want to have to do that. Let’s keep it easy for me. I’m going to click the Run button and assuming everything’s good, it’s going to go ahead and start up the app. Then let’s go hit up localhost in our browser. In my browser I hit up localhost:3000 and now if everything works right and I click on this tab, which should happen, is it’s going to query Salesforce and it’s going to pull back my two folks in that district, sure enough, it pulled back Leslie and Joan and any party information. Now remember, when we added Joan we didn’t actually set a party, so it didn’t show up there. If I switch back to code, I’m also pretty chatty with the logging, so you can see the JSON that came back from that query, and so you can also look at this yourself as you’re investigating what we’re doing in the app, you can see it’s printing out the data it got.Now let’s go back to Salesforce and just have some fun and prove that we didn’t do anything too weird here. Let’s go into our records and let’s add a political party for Joan, so we can prove that this is really pulling this information live. Let’s go to Voters in one of our applications. Let’s find Joan, and we want to go ahead and edit her and for her political party let’s go ahead and make her an Independent and click Save, and now let’s go back to our application, we can just refresh it. It’s going to do another query, and she’s an independent. Great, so we’re showing that this application is pulling data from Salesforce, integrating it with itself so people could, you know, mash this up or use this in different ways.

Client-side Caching with Conditional Requests

So now we’ve started integrating the Salesforce application environment and with our application let’s keep moving on and talk about client side caching with conditional requests. This stuff gets in handy when you want to support response caching. REST allows conditional requests headers that follow the standards defined in the HTTP 1.1 specification. So this makes it easy to do client-side caching with data and being able to make requests and find out, hey if anything didn’t change, don’t give me back anything else and I can keep using this cached version. Now this is a little bit of an interesting service because it’s not fully fleshed out to everything. If I’m using the Account object in Salesforce, that’s it, I can use an If-Match header, so this gives me some capabilities for only if it matches certain record types. If-None-Match, I can also do get individual records and make sure, but it requires the use of a thing called an Etag and Etags are only associated with the account, so I’m really looking at differences in these Etags and only telling me if things have changed. If nothing’s changed, then don’t give me anything new back and I’ll just use my cached version. If-None-Match, same as it goes for that. So if I’m using anything else then I can use an If-Modified-Since header. So this is one where the HTTP client, that could be your browser code, may optionally supply to the server when it requests a resource. If it supplied the meaning is, I want resource whatever, but only if it’s changedsince time t. So this allows for client-side caching and it’s still really handy for all the other sort of objects type. So I can say only give me something if it’s modified since yesterday or if it’s unmodified since a certain date then give it back to me. This works against individual records, which can be pretty cool. So this is helpful if you’re trying to do a speedy mobile app or just any sort of client-side caching and you want Salesforce to be smart about giving you back things that have only changed in a certain time window.

Maximize Round Trips with Composite Calls

One of the cooler things in the REST API is composite calls. So we’re going to spend a little bit of time here on this and then jump into a number of exercise that use it. So really three types of composite calls. We’re going to drill into all three. So I can batch up a set of operations, I can do a bunch of different things, it could be different GET, POST, PUTS, different objects, I can put those all into the same one request, which is pretty nice. I can create nested records. This is pretty handy and we’re going to do this where I might be creating let’s say a voter and a donation at the same time, that donation record clearly has to depend on that voter record being created first. I can’t have them out, they have to work together. So I can create nested records together. And I can also create a set of unrelated records, still of the same type, but I could almost use this to just insert, let’s say, 10 different voters all with one request. They’re not related to each other, but I want to batch them all up into a single call. So let’s look at all three a little more in depth. First off, as we’re dealing with this sort of batching, you have a batch resource URI, so you’re hitting services/data/version/composite/batch, and I’m submitting that in, and when you’re looking at that you can actually execute up to 25 sub-requests in a single request. Now remember, each one of these sub-requests counts against your rate limit, so this isn’t necessarily a way to cheat and say, hey it’s going to look like fewer API calls, each one still counts as an API call, I’m going to do this though if I want to maybe simplify the request itself and I just want to send a bunch of things at once versus having a chatty application. These are all very independent operations. So one cannot pass data to the other one, there’s nothing related between them, these are all simply independent operations and, again, I could do a bunch of GETs, different endpoints, whatever it is, it’s simply a way to execute a bunch of things serially, and these are executed serially in whatever order you put here. If one of these sub-requests fails, any commit made by another sub-request isn’t rolled back. So that’s fine, these things are very much independent of each other. As you can see, I can use s objects, I can do queries, I can do search, I can do all sorts of things within this sort of batch. And as I mentioned, no context between them, I can’t pass the result of one into something in the other, and these all executed serially. So again, this can be very handy in some cases where I want a bunch of sub-requests bundled up together to maybe, let’s say, get back three different things all at the same time, and maybe they have a related field that I know client-side and I don’t want to make three calls, I just want to make one call and get back three different s objects that are all somehow related to each other. The next option is this sort of thing with nested records, so I want to make sure that I’ve got the relationship in the right spot and I want to have a Tree and SObject URI. So you see composite/tree, I’m going to do the tree off of the Voter, so in this case, is we’ll actually do here, and when we do the exercise I might have a new voter, and then I want to attach donations to that. So I want to create all of that at one time. The root record has to match the URI SObject. So I can’t POST to voter and then create a donation at the top level. I have to match those two. So I have to make sure that I’m thoughtfully putting this together, not accidentally slamming the wrong object types into the request. But as you can see, I have this nested relationship or master/detail, both work here. So whether I’ve created a nested relationship, a lookup, or a master/detail record type, both of those work fine within this structure and I’m in good shape there. The final type is this sort of general grouping; I just want to create multiple unrelated records of the same type. So once again, you have this sort of Tree and SObject URI and this is where I’m just going to be pumping things in there, it’s an array of the same record type. I can actually do up to 200 records in a single request. These are not individually committed though, these are an all or nothing transaction, so this is where you might go back to the first option of batching if you really wanted to treat these as individual transactions, not an all or nothing transaction. So again, this can be handy if you want this behavior and that may be the case where I’m inserting a bulk of data and I don’t want to have to parse through which ones failed and try to retry them individually, but again, be aware of that.

Demo Description: Performing Composite Calls

Alright so now let’s do a fun demo with this. We’re going to go ahead and issue a batch query using the sort of batching, we’re going to create multiple records via that tree endpoint, we’ll go ahead and create some nested records, which is cool, and then we’re going to create multiple records using the Batch. I wanted to show you how to do that as well. So we’re going to do a few different interactions with this sort of endpoint. Let’s jump in.

Demo: Performing Composite Calls

We are back here in Postman. So we’re going to issue a batch query to start with using the REST endpoint, then we’ll go ahead and create some multiple records, create nested records, do some batch records. So let’s start off with the batch query. So let’s go ahead and jump into the folder that has the different scripts in code that you downloaded for the course. In one of the files in here, you’ll see restbatchquery.txt, so open that, select all that content, copy it, close it, jump back into Postman. This will end up being a POST request and the body is going to be the raw application JSON and let’s paste that in. So let’s get the URL first before we clean up our data. So the URL we’re going to post to is your URL, whatever you got back from Salesforce when you logged in, remember, go look at your REST login if you want to see what your URL is, in this case mine is na30. So na30.salesforce.com/services/data/version/composite/batch. Okay so the version and the queries has to match the version in the URL too. So you see within here I’m doing version 35. If I do version 34 up here, this is not going to work. And again, I’ll neither confirm nor deny how much time I wasted realizing that point. So make sure that those things match. Next let’s go ahead and before we forget, let’s make sure we put the Bearer in here. We should still be able to use the token, depending on how quickly you’ve been doing your course work here and not taking hours in between your lessons, this should still be a valid token. If not, simply call the endpoint again and get a fresh one. And I shouldn’t have called this Bearer, this is actually Authorization Bearer space long value. Okay, so this isn’t going to work right now because these aren’t valid values. So let’s go into our Salesforce app and grab the right ones. So within Salesforce, let’s go to our app launcher, let’s go to Sales, let’s go to Voters, let’s grab Leslie’s ID, save that from the URL, copy that, go back to here and let’s go ahead and paste that into voter, so we’re going to go ahead and get the voter at that URL. Now I want to get a precinct, so let’s go back and let’s go ahead and look at precincts and we’ll go ahead and grab the 3rd District, that’s all I have available, let’s take that record Id and copy that, let’s paste that into the request, and then finally, so you see I’m doing three GETs that are really unrelated, GET me the voter here, GET me the precinct, and now go ahead and GET me the voter donation here and let’s go back to voter donations. Here we have Voter Donations, take this first donation at point 0 here, let’s go ahead and save that value, let’s paste that in here and I can actually pick which queries too, so I’m doing the RESTful request voter donation, I’m saying give me the field’s name and candidate name, so that’s pretty neat. So I can also down select because if I’m dealing with mobile apps, I’m dealing with other things, I may not want that whole payload. I want the minimum back because bandwidth is at a premium and data transfer costs are high. So let’s go ahead and shrink down what I need. So I’m doing three disconnected requests with a valid authorization header to the composition whack batch URL. So let’s scroll on down and see what came back. So results, hey hasErrors false, that’s a good sign. So first off I’m getting Leslie back as my query. The second request also good, I got back the precinct data, which is what I asked for. And then finally, the last one was also a 200 and I got back a very nice tight payload of just the donation. So pretty neat. I requested three objects with one request, got back them all, and I can see the individual details of each one, and I saw the benefit of shrinking it so I don’t get all these values back by actually passing in a tighter request value, by picking which fields to show. I’m going to go ahead and save this because it’s a good habit for me to go ahead and save my request, so this is going to be REST Batch Query, may want to use that one later, so let’s add that to the collection. And let’s add another query here. So what I want to do is create a bunch of new precincts. I only have one precinct here that’s not very exciting, let’s go ahead and create a brand new request. So I’m going to go ahead and steal some of this URL so I don’t have to type the whole thing over here in the New tab. This one though, what I’m doing is I’m doing version 35, I’m doing composite whack tree whack precinct__c, and let’s go ahead and add the headers before we forget, this is an authorization header. Let’s go ahead and steal the value from our last request, Bearer and then the big value. Let’s put that in here. Great. Now this is going to be a POST because once again I’m querying here, I’m getting something back or I’m really pushing this request here.So the body is going to be raw, it’s going to be, once again, JSON format and where are we going to get that format? As you can imagine, I’ve already given it to you. So let’s jump back to our folder, and within here you’re going to have a file called restobjecttreecreate. Here’s this last one, I’m going to go ahead and copy that, and I’m going to go ahead and paste that in there. We already have the 3rd District, so let’s go ahead and finally get the 4th one in there. And so what we have here is a JSON payload, records, multiple types, it all has to be the same type though, it’s all type precinct, but two records themselves. Now referenceId, these just have to be unique values. I don’t really see where this gets stored or where this matters, but these do have to be there and they should be different from each other, so as I add them they have to have different reference identifiers. So you see I’m sending in this JSON payload, I’m passing in an array, two different precincts. Let’s go ahead and send that in. If I scroll down I can see here, I got back no errors and I got back the referenceId and I got back its new record Id, so I can confirm this via the API, let’s also confirm this via Salesforce itself. So back in Salesforce, I can go ahead and click on Precincts and sure enough I look at All, I already showed them, but now I have the 3rd, 4th, and 5th District. So I save some time by doing this sort of bulk input. So we’ve made a nice clean request, we got back identifiers that proved this worked, and I can use the APIto precede the information here, again, without manually keying all this in. So that was the first two types. Let’s go ahead now and do some nested records. So I’m going to save this one, just to be safe, this was REST Tree Insert, Add to collection, fantastic. Let’s create another one. Now this time what I want to do is create nested records. I want to create a bunch of voters and their corresponding donations. So let’s again steal some of this URL, I’m going to go ahead and copy this, put this into here, this will be another POST because, again, I’m sending it some data. Alright, so instead of having this, I want to do this to the Voter object. So I’m going to pass this in to composite/tree/Voter__c. Once again, let’s jump in here on Headers, add the authorization header, we’ll steal that from our friend here,sharing is caring, here we go, let’s paste this in. Alright so I’ve got my authorization header, I’ve got my URL, all I’m missing is a body, which is important. So let’s click raw, this will be XML, that’s also stealing the content from the last one, we don’t need that. Let’s jump back to our folder and there’s a file in here called restnestedcreate-1. So let’s go ahead and copy this all, alright we’ll paste that in, we’ve got a bunch of data in here. Let’s make sure we have a valid precinct. Of course this wouldn’t be there from when I originally created this, so let’s jump back into Salesforce and let’s pick one of our new precincts. Let’s go ahead and put these folks in the 5th District, why not? Save that, jump back. Let’s put Ann in the 5th District, that’s fine. So what we’re doing is we’re creating Ann Perkins, she’s an independent.We’re adding some voter donations. So I’m adding a relationship here, it’s a nested record type, so you’re seeing records again. I’m creating a voter donation, $1000 to this candidate and $500 to this candidate, $100 to this candidate. So we’re creating three different donations for Ann as a new record type. Let’s go ahead and send that in, what I get back is results. It created the record and probably the three donations. Let’s go ahead and jump into Salesforce and confirm it. Let’s jump back to where I can view the Voters, sure enough I’ve got the lovely Ann Perkins and if I check her out I can see she should have three related records. First of all here’s all the stuff I created, she’s in the 5th District, that’s great, and she’s got 3 donations, that’s great. So I’m able to create these things as one big transaction, create the person and then create the donations all in one single commit. So I have one more I’d like to do. Let’s go ahead and create multiple records via batch. In this case it’s a few voters with no donations, right, I want to have independent adds, it’s not all or nothing, I want to make sure that this is just easy. So let’s go ahead and create one more request, I’ll save this one, just so we have it. As you see, our collection is growing, that’s a good thing. Let’s create one more, once again, I’ll steal some of the URL from here, and this time, again, I want to create multiple different records, but because like before I don’t have to specify the type because I’m going to embed a few different things here, so I’m going to submit it to the batch endpoint again. So let’s go ahead and steal the authorization token from one of our previous requests. We’ll put that in there. Once again this is a POST because I’m going to be creating a bunch of records. Its body is going to be JSON, and let’s jump back into our folder and grab a file and the one we’re going to be looking at here is restbatchcreate. Let’s go ahead and paste that in. In this case what I’m doing, I’m creating Ron Swanson, Andy Dwyer, and I’m getting back the full list. So I’m creating two new voters, different parties, they’ve got their mailing address, they’re looking good, that’s fine, they’re all complete data, they’re independent from each other, right, so if one succeeds and the other one fails, it technically doesn’t hurt me. Let’s go ahead and make sure we’ve got a valid precinct here. I’ll go pick the 4th District and put them in here. Let’s grab the ID, save that, jump back here, and let’s put them both in the 4th. Great, we have everything, so now we’re going to do two different independent creations of voters. I’m going to get back the full list so I can actually see both of them. Let’s take a look. So I created both, got 201 back, and then when I get my list of things back I should be able to see recent items, I can see Andy and Ron show up in the list. So it went ahead and create those records and added them there. I can confirm that by jumping back into the environment, I should see these new voters, sure enough there’s Andy and there’s Ron, neither of them should have any donations, it’s great. So I’ve gotten those added then independently. Finally, for good measure, I realize I forgot that I wanted to not just create Ann as a nested record, but let’s use this exact same content, let’s delete that, go back into your folder and there’s also a restnestedcreate-2, I wanted to create one more record just so we have a good set of data in here, so copy restnestedcreate-2, come back in, take that request where we were creating this for voter, where we did Ann before, the nested record, is I want to make sure we just have some good data in here. So let’s go ahead and take the precinct from this last one that we’ve just put them in on. You can pick anything you’d like, again, we’re just trying to get a good set of data in here so we can keep manipulating that and having some fun with that. I’m going to pick that precinct, once again a voter donation, everything else should be the same. Let’s submit Ben. I’ve got two records, and now let’s jump back into Salesforce and now by the end of this exercise we added Ann Perkins, we added Andy, and Ron with no donations, we added Ben who should have one donation, if I look at his related, and sure enough he does. So we added some great data in here showing that I can do some things in bulk, I can do some things with nested, I can create records of all the same type and make them all or nothing, or I can create a bunch of records via batch if I want that flexibility.

Building Custom REST Services

We just saw a good example of composition operations, which showed some of the flexibility and power of the REST API, but that still always can’t be everything. And there may be times where you want to build your own. So much like with the SOAP API, you have a lot of choice within the REST endpoint to build your own services using the REST endpoint. So I could create a special URL or once gets created, and you’ll see it’s at /services/apexrest/ whatever your class name is or however you define that endpoint, we’ll see how to do that in a moment. It uses Session ID or OAuth Security, so you’re in good shape there, setting in that Bearer token. You could XML or JSON into this, so again, I could pass this in from any sort of application, it doesn’t matter what it’s expecting, and then I can choose my urlMapping, much like a regular REST service, you see there’s an @Rest resource decoration, and then I pick the urlMapping. What do I want that resource URL to be? How should this look? And so I could do /votersWithDonation because I want to pull back voters with aparticular thing and maybe get back the value at the star that actually stores the value, whatever it’s supposed to be, but I can support wildcards and do a number of things as I map a URL. You see I have to have a global class here, unlike the SOAP one I’m not decorating or I’m not using like a web service keyword, like I did with SOAP, it’s a little different. If we jump down, you can see I can use my own classes, but then I’m using the HTTP verbs. I’m choosing what I want to do here, so I’m saying when I do an HTTP GET against that REST resource, execute this operation, that’s that I’m seeing here. So the user never sees a function called GET voter. When they make a request to that REST resource via HTTP GET, this operation instead actually gets called. Once I’m within that operation I have access to a few objects like RestContext.Request and response. So I can get information about the request, I know where the user was coming from; I know what they were asking for. You can see here that I’m able to pull out the requestURI and suck out the substring, grab that last thing after the slash, which for me would be the voterId, so I can pull out that voterId, do a query, and return it just like I did with the SOAP service, in this case though, going full REST. Much like before, the operation does use the system context, so be very careful because anything I do within that code block, any customer can invoke, within my organization of course, any user can invoke. So I want to make sure I’m not doing anything sensitive and if I am, then I want to be sure that I’m checking that calling user in my operation since Salesforce won’t do it for me.

Demo Description: Building a Custom REST Service

Here in this final exercise of the module, we’re going to go ahead and build and test a custom REST service. We’re going to build it in Salesforce, of course, and then we’re going to call it in Postman and our application, so now we’re also going to get this involved in our app. So let’s go ahead and jump in. What we’re going to do is create a custom class; we’re going to define an operation that returns an aggregate data. What I want to do is I want to return the voter with whatever donations they’ve made so that our custom app, our Node.js application, can do that when you click the button, it can pull back the related information. I’m going to decorate that class with all the necessary REST annotations. We’re going to test it from Postman and then we’re also going to go ahead and consume it from the Node.jsapplication. So again, we can continue to integrate this.

Demo: Building a Custom REST Service

We’re back at Salesforce and what I want to do here is go ahead and from here let’s go to the setup screens because we’re going to build a brand new class that represents our custom REST service. So jump into the Setup Home, let’s go to Custom Code, Apex Classes, and we’ve already created one before that represented our SOAP service, this is the SoapVoterService, let’s click New and now we’re going to build a new service. So let’s jump over to the folder that has all of our application code from the course and there’s a class in here called apex_customrestservice, open that up, just do a copy, copy all that content, close it. Let’s jump back to Salesforce. Let’s paste all that in there and let’s take a look at what we have in here. So I have a top level class, I’ve decorated that with a RestResource, the urlMapping is VotersWithDonation. Just like I showed you in the code sample, I’ve got an HTTP GET, I could add all sorts of other operations, POST, PUT, DELETE, whatever that would call the appropriate class. And it’s simply going to return that data. So now I know when I call this service I’m going to get back a composite object and a custom object. Right, I created a new class called VoterDonation that has the name, the party, and then a list of all their donations. That object doesn’t exist in Salesforce, it’s not even a custom object. I just built a class, I’m going to populate that class within my code and then I’m going to return that class. So I’m returning not even a standard object, I’m just doing something that’s entirely code-based. Let’s go ahead and save this. And this class is instantly available now for consumption. So let’s go ahead and jump into Postman, and we have another tab here for this new operation. What we want to do is we want to do a GET request. Now we are doing GETs, and so let’s go ahead and do a GET to https and I’m hitting services/apexrest/VotersWithDonation/ and I need to go ahead and get the ID to that of our friend Ann Perkins, so let’s jump back into Salesforce and let’s jump back into our application so we can get into the Voters application, and let’s find our friend, nope I don’t want Andy, let’s go ahead and grab Ann, we know she has three donations, so that’s going to be more interesting. And let’s paste that to the end of the URL. So give me all the VotersWithDonation for that particular ID, that’s what I want that. So let’s add the authorization header, make sure we don’t forget that, and let’s take the value from one of our previous requests that we’ve been doing here, you should still have those, again, if it’s been awhile between you executing these exercises, no worries, just execute that REST login again to get a fresh one, and that should be good. Sure enough, what do we get? We got back our custom response, VoterParty, VoterName, and Donations. I’m getting back all three donations that she’s made. So I’m really easily able to get that back, which is pretty cool. Now again, to really show off some things, what’s cool is that I can also jump into the header and say let’s throw an Accept header in there and let’s go ahead and make this application/xml, and now I can get Ann back via XML, which is also great. So I’m showing that my service itself can be ignorant of the request format that the customer or the user wants. It can be something they’re deciding at runtime as to what format they want. So I’m able to build this custom service and then choose which format I’d like to use. Now let’s jump into Visual Studio Code and take advantage of this. So here in Visual Studio Code what I want you to do is jump back into the code view, we’re still in our VoterTrax application, and we’re going to be on a different route now, lookupvoterdetails. This is a part of that precinct page that when they click the button I’m actually doing an AJAX call back to the other endpoint to pull back information about that. I want the details of the voter you just clicked on. So we’re already doing the login. We did that before. Nothing we have to change there. Let’s go ahead and change this URL and in this case we want to retrieve the voters along with the donations, what do I want to call here, we have VotersWithDonation, fantastic. And that’s good. So let’s go ahead and keep that. So I changed, all I did was change the server name, the rest of it stayed the same. Here’s the URL. Now if you called your class something different or you did your URL different, rather, then go ahead and change that. If you didn’t, you can go ahead and keep that the same. And that’s the only thing you should have to do here. Let’s go ahead now and run this. Switch over to the Debug view, start that up. We’re in our application, if you click on the precinct view, if I click on Leslie, sure enough, she has one donation to Garry Gergich for $100. I don’t think Joan has any, so nothing comes back. So this actually is making an AJAX call back to our new service that we built that’s pulling back the voter with all of their donations, which is pretty cool. So I showed how we’re using the REST API to pull back default objects for these two and I showed how we’re using a custom REST service pull the details for any individual one where I want to pull up some additional information. So pretty cool to see how you can do integration of these services back into your applications.

Summary

This was a fun module. I like the REST API a lot, I think it’s fun to use, there’s a lot of good pieces of it, a lot of areas to explore. So we saw a number of things here. We kicked off the course, or we kicked off the module, we looked at the anatomy of a REST call using HTTP verbs, using resource identifiers, using a different authorization, authentication model, and then we jumped into that. How does OAuth work? How do I set up a connected app? How do I then pass in the right values in order to get back what I need? Looking at the REST objects, the same sort of object model I have with SOAP, actions are a little different, it’s not the same breadth that SOAP gives you, but I still have a lot of things I can do with the REST API. We dug into the HTTP response codes and saw a number of them. There’s a couple others I didn’t list, but the core ones I listed, and showed you kind of what Salesforce interprets for each one of those. We talked about conditional requests for client-side caching. We dug into composite calls and what that means to be able to batch together requests, do all or nothing sort of requests, or even do nested things. And then finally, we looked at building custom REST services. How can I extend the core of what Salesforce does by building a custom service and still exposing that in the same RESTful fashion, exposing XML or JSON the same way. Hope you enjoyed this module. The next one jumps into batch requests, which is really important when I’m doing this sort of bulk API and I want to be able to submit a lot of things either as a query or in terms of an insert, update, delete operation. And so we’ll dig into that and I think you’ll enjoy using that as well.

Advertisements

Leave a Reply