Using Apex for REST Integration

hello everybody and welcome to this webinar thanks for joining us a good morning or evening or afternoon depending on where you are joining us from today we are going to be discussing using apex for rest integration the kick things off let me introduce our excellent speaker list to talk about today now today is actually gonna be a little bit different because a lot of our webinars are very introductory to a topic and today we are going to do a very deep dive into rest integration using apex and over to talk about this we’ve got two experts on the topic both from CRM science we’re going to show you some great production worthy code about how to get this done so I’ll be encouraged I don’t you guys introduce yourselves hi my name is Lamia egg and I’m an architect at serum science which is a consultancy specializing in deep sales force expertise we handle handle integrations every day so we’re really excited about sharing some of our experiences today then I’m Kirk Stuckey the app exchange lead here at CRM science which means I get to have a lot of fun with the Salesforce partners and their apps on the app exchange I’m also one of the organizers of our local developer user group here in Philadelphia alongside ami called Philly Philly force people and if you are not familiar at the center my voice my name is Josh Burke I’m a developer evangelist with Salesforce calm and you can catch me on Twitter at Josh Burke this is our forward-looking statement aka safe harbor slide basically dynamic and purchasing decisions based on future looking statements that myself on the curb might make we do not attend to make any of those but we will try to call them out if we do now you can follow us on your social media channel of choice we are on Twitter our official account at Salesforce dance you can give us a shout out either during this webinar after with the hashtag force webinar we also have a Facebook page a LinkedIn group in a YouTube channel and usually when the first questions we get is yes this is being recorded give us about a week or so and it will be up on Developer salesforce.com you can find it through the same URL as your registration now if you have any questions don’t feel like you need to wait into the end of the webinar mommy Kirk myself are going to try and keep somewhere around five to ten minutes towards the end to handle some of your questions however we aren’t also going to be taking questions during the webinar itself and go ahead and go to the question panel within good webinar and I will try to answer them in real time and then we’ll pitch some of them towards the end to the three of us and if we do not get to your question you can always go to developer Salesforce comm slash forums our agenda is very straightforward I am going to give you an extremely short introduction to rest api’s just to make sure that we’re all on the same kind of level when we’re known what we’re talking about and then we’re going to take two big demonstrations of how to handle outbound calls to third-party services or to have a handle in button count inbound calls into the Salesforce platform using Apex and then we’re going to talk briefly about using apex and unit testing for these kind of cases now Salesforce has a wide variety of api’s we’ve got great family of api’s from a REST API our granddaddy on the platform SOAP API our metadata API for tracking the configurations or real-time notifications with streaming API and our ETL friendly bulk API as well as specific REST API is for chatter analytics and cooling and all that running on top of our identity cloud being that it is secure using OAuth so that you know that it is both encrypted and authenticated but today we’re talking very specifically about REST API s and REST API is work in a very specific way basically they work exactly the same way that your browser works when it goes to say cnn.com but it goes to cnn.com it is doing what we call a get HTTP request that’s a get method in HTTP so it goes the website it asks forget and it gets a read in this case cnn.com gives it some HTML your web browser will then take that and convert it into the web page that you see in your browser if you say posted something through an email form well that would be a post request you’re going to create some data on the server rest api’s formalize that down to a series of endpoints and so say if we get to the URL we see at the bottom of our account slash account ID we’re going to get some information about that specific account ID record whereas with post we would create a new one with put we would update an existing one and if we did a delete request against that same URL then we would probably delete that record now rest api’s do also have some more complicated functions depending on the end point but this is the basics of how to get it to work and the two main columns are if you can handle HTTP within your language and JSON within your language are probably well equipped to deal with a REST API and on that now let’s ask our first

question how can I call out to third-party endpoints well as it is apex is very well-suited for this first of all as I was saying if you can handle HTTP you can handle JSON you can probably handle rest call-outs and Apex can handle both HTTP and JSON on a native level it also has some convenience functions which you’re going to see with some of the stuff that Omni is about to show us when it comes to handling things in the background using the app future annotation or we could even schedule things from a day to day basis if you wanted to say call out to a third-party endpoint to get some updates on some records you could do that every morning by doing scheduled events but to show us some more specifics I am going to hand things over to Kwame making him presenter and ami show us what you’ve got when it comes to outbound calls with Apex thanks Josh so I’d like to start by showing everybody a use case for admin integration so let’s set up a scenario where we’re working with a retirement community where the residents access a customer community to make and track personal requests internally we then store these requests as cases now we want to make it easier and quick for the residents to create these requests so instead of letting the residents add title description and type and some other on for information let’s create a more interactive experience where they just tell us what they need and we figure out the rest so we can do that by using IBM Watson and we can use an API a service called natural language classifier within IBM Watson the service takes a sentence or paragraph and lets you and tells you what class it belongs to a class in this case would be a case type or a category there’s quite a bit of work that needs to go into setting up the service and we’ll save that to to another webinar but let’s see how this may work so here’s a very simple demo of the use case we just discussed I have a simple page that solicits a request description from a user and so when I enter something like my toilet is leaking and I submit it goes to Watson and gives us the likely class for this description and it says it is plumbing and it’s 78 percent sure that that’s the case and now we can use this information in different ways we can just store that information and use it for case assignment or show it back to the user and ask if we’re right and and potentially show other likely types so let’s show you a couple more coats so you see how it works so let’s try something like please hang a picture in my bedroom so every time I click Submit it makes a call-out to Watson and gives us the response so for please hang a picture in my bedroom what some things that is 88 percent sure that this is type install let’s do something like I have spiders in my bedroom and submit that and you can see that it’s 80 percent sure that the type is extra now every time we make a call-out we can log that transaction so let’s look at how that looks like and let’s choose the last one so you can see that we have a lot of information that we can log in this case we log the the endpoint including the resource we can just put the resource because every API can have multiple resources so you usually want to do that we can say what the method is we can show you what the request header is and in this case we can see that the body request that we’re sending is basically just it it’s a JSON object that is very simple to value pairs it sits as text and it just said it’s the description parentheses you can say that where you can see that we’re also

getting a response from Watson and let’s make this a little bit bigger so the response from Watson is also a JSON object and it starts with for very simple value pairs and then it has another value pair that is an array that you can see from this square bracket and inside of it it has several objects that are built from two value pairs each class name and confidence the reason I want to show you this is because when we look at the code we’re going to create an object in insert in the class that mimics this JSON object so and so before we even can make a call out though we need to take care of authentication for that we usually have this simple visualforce page that allows a user to save their credentials every time we save the credentials we actually make a test call out to very verify the creds so what I’m going to do now is to cause an error in saving this and what I’m going to do is I’m basically going to change the idea of the classifier I’m going to add an X here I’m going to save it and you can see that it didn’t like it it went all the way to Watson and what’s inside I don’t know what you’re talking about let’s save it back and now it works great so if we go back to the log we can see that it went to Watson and it got for a four hour basically it says I didn’t find this classifier that that you mentioned because it I had this extra character in there and then you can see that it sent it it sent we sent a response to correctly and we receive it 200 with the all the information so that’s the that’s the demo let’s look at the code so now that you’ve seen an example let’s let’s see how this is how this can be coded we’re going to review a single class that handles the called portion of the demo before I start though I want to say that normally this class would be very generic but it make I made it a little bit more compact so it’s it’s easier to fall so it’s it’s somewhat specific to what’s an API normally you would see it you know a lot more generic so the first thing that we’re going to do is to create an internal class within this class we can use this to house information about the requests and more importantly about the response so you can see here that we have the respond code a body of the transaction that came back whether this was a successful transaction or not the type is going to be basically the class that comes back confidence is the percentage that Watson is is confident and the text error is going to just be something that is we can populate in case there is a an error in the transaction so the caller knows what to do so basically we’re going to use this to return a value to the to the to the caller we have a the class here that shows you that basically when you instantiate this this class internal class it basically figures out what’s a success and this is another opportunity for us to customize based on the specification of the API the next thing that we can do here is create a couple of internal classes that we can use to help us for deserialization so when I showed you that the how the transactions look like the JSON that comes back from Watson this is exactly what we’re trying to mimic here so we have the the four value pairs inside this class which we called classified container and that includes the just generic stuff and it has the the top class it also has a list and which is an array of this other internal class called classify class and that’s another object that has the two

value pairs that has each class name and confidence so this very closely mimics what we see on on the transaction and that will help us deserialize in in just a little bit so now we have a class we basically anytime you want to make a call out you call this class this method and you just have to send it the description and what you are looking to get in response with is the response variable that or internal class that we in created before so first thing that we want to do is we want to instantiate one of these responses next thing we want to do is we want to get some of these variables or from custom setting like the endpoint the resource and also we want to set up the get so these are the these are the kind of things that usually you you save in a custom setting and actually if you want to you know make a really nice generic code class you would actually also send that into the class itself so before we actually make a call out we want to do we want to make sure that we can actually make the call so first of all let’s try to figure out if we can if we hit the call it limits if we do we can set up the error text in our response and also we can send something to the log second thing that we want to check is to make sure that we have all the credentials so the username the password that we have the endpoint and it’s not blank and if it does again send an error and send something to the log now with that out of the way we can start preparing our code so the first thing that we need to do is like just said apex has HTTP requests HTTP response and HTTP variables objects that you can create HTTP is what’s used to actually make the call out it has a method to make the call out the request is what you set up beforehand to to send all the right information and the response is what you receive receive back from the API so first thing that we need to do once we have these variables is want to set up the request we want to set up the endpoint in this case it’s combination of the the base endpoint and the resource we want to set the method that we we created before which is a get in this time in this case and we want to set the time out this is the max time out for apex which is two minutes we’ll just set it to that we want to now take care of authentication Watson ap is our basic authentication based and to do that what you have to do is to take the username again we’re going to take it from the custom setting and you have to take the password put a comment between them you make a blob out of it and then use a Salesforce or apex method to and base64 encode this blob and then it creates this alphanumeric a character long character and you put it in the header of the request with the Thor zation as the as the value we also have to set up a few other things that are required by the API except is is a normal header and then the content type is application JSON because we’re sending and receiving Jason this is some usually when you read through an API documentation you want to see exactly what is required by the by the API sometimes or other funky headers that are required then you should probably add lastly we want to set up the body and in this case if you remember from the log we just have to say text it’s it’s a very simple JSON object with one value pair text in the description so our request is ready so what we can do now is we can try to make

the call out we’re going to put it in a try the because things happen dissent sometimes fails and that’s an exception deserialization fails sometimes and that’s an exception so you want to you want to put all that in a try so what we need to do is we basically H is our HTTP object we’re going to use the send method and we’re going to send it a request and we’re going to return a we’re going to put all the response in the response HTTP then we’re going to put our the the status code and the body of the response into our own internal class that will also tell us that whether it’s successful or not so we can check that and if it is successful we can start working with the response so you’re getting a response which is a JSON object what we have to do first is we’re going to use the classify container that we we created before that’s the internal class this really contains a second internal class and we’re going to deserialize it or basically deserialize the body into the this classification variable so first thing we need to make sure that we actually go to response back so it’s not no it’s not empty and so forth if it is again sends an hour value the error text and instance not something to the log if everything is good then basically we can start doing the real business of what happens once the response comes back and this is mostly where most of your code is going to happen when there is a call because you know you know you have a some business logic to to handle in this case it’s very simple because you know we just have to do a couple things first of all we want to again log that this was successful we can take the top class from because we DC realized into classification we can very simply and easily move that into the response that we are going to return to the caller and then we’re going to just very quickly go through all the classes make sure that we find the correct class and get the confidence once we get the confidence which is the percentage we can just break last few things that we have here is just to handle if the transaction failed or if there is an exception in the try so we just have to log the air and return or value the return and finally we just return this this internal structure that the caller can then decipher to figure out what to do next so that’s really the very simple version of what you can do when you make a call so before I hand it off to Kirk there’s couple thing I want to chat about with you so during the cord review I briefly talked about the fact that we use basic basic authentication but that’s not the only type of authentication that can be supported for codes to extend away external API s so I want to quickly mention three common types of authentication that are used by services that you norm all you want to call out – the first is unauthenticated services you simply make a call and receive a response these are typically read only type of AP is like Twitter CNN so forth the next is basically an occasion like Watson with basic authentication you usually save the user creds in a custom setting and then you use them when you make the call and the last one that I’m going to cover today is is auth which is a little bit more involved though of authentication and you normally have to code an OAuth handshake process that basically allows the user to enter their credit directly into the service that we need to go out to and once that done that service sends you a unique token that you can store in a custom setting sometimes it’s multiple

tokens if you if you have a refresh token and then when you make the call you get these tokens from a custom setting instead of the actual username and password so since we have a limited time today and actually tons more to cover I want to mention just a few more things before moving on to inbound so typically a rest service they usually use JSON responses and and requests and Salesforce has several methods to easily serialize and deserialize JSON objects both untyped and type so it’s very useful occasionally you see payloads are XML based even though it’s rest but even for that apex provides very convenient methods to to write and read XML another consideration is the fact that you sometimes need to delay commits and you have to do that because DML and cox operations have to be in a certain order at times example classic example that is when you make a call out just to find that your token expired at that point you need to make a call out with your refresh token and then use the return session token to make the original call again so in that case you actually made three cards in one execution and you also need to commit the token back into the custom setting as well as maybe logs and you have to do some other DML for some other information so what you need to do here is to actually keep all these records in memory until your last go out and then commit all at once next thing is the platform also gives us the ability to make a synchronous co-op’s so I usually like to have the calling method synchronous and then when you need to specifically make it asynchronous you create a in hat future pass-through method to to call that and lastly we can use codes in in batch processes which is actually really useful when you want to do like really large sync jobs one of the main things that you want to be worried about here is to make sure that your batch sizes are not too big to cause CPU limit exception so even though you know sometimes you you know you can make more call-outs you actually don’t want to make all these codes because the processing after the call-outs will take just too long so that’s a very brief overview of outbound integration i’ll pass control back to josh to expand on some inbound customizations with a fix so again thanks Josh thanks ami now that we’ve covered making call-outs to the remote systems from Salesforce we’re going to talk about the inverse how can we set up Salesforce to accept inbound requests from those remote systems and using that retirement community as an example let’s go ahead and imagine a scenario where they have an existing third-party service that handles community member tickets these tickets again would be things like residents needing assistance changing light bulbs or moving furniture and upon the creation of these requests the organization would like to send these tickets and their information into Salesforce and of course one way to do this is going to be through an exposed Apex rest class now the standard Salesforce API is are great but custom effects rest classes are going to offer many advantages and you’ll see in the upcoming demo we can include custom processing of the request details on the salesforce ID and you’ll actually see how we take the request payload and turn it into useable objects we’ll be using the tablets of the information to look up contacts in cases and and begin working with those and because of this flexibility you can design with a limit efficient processing pattern in mind you can even provide additional levels of programmatic access control and you know a main benefit for me is that they’re also package’ below now you can allow these additional inbound api capabilities into your apps as well so again our flow is going to be that a community resident is going to create a new request or a new take it in their system and these details of the ticket are going to be sent over to Salesforce to a Salesforce URL endpoint as a JSON formatted request and once that request is received our Apex rest class on the sales for Salesforce ID is going to process that request and then return back some sort of response to the remote system at that point the remote system can look at the response and determine if it was successful or if

there was an issue and if there was an issue make amends deal with it if necessary so if we take a closer look at the makeup of an inbound rest class you’ll you’ll see that there’s a few characteristics that are actually unique to this type of class the first one is going to be the class annotation of addressed resource this mocks the class in a way that allows it to be exposed and treated as a web service immediately following there is something called the URL mapping this defines part of our endpoints URL and a typical endpoint is going to look like at node salesforce comm services slash apex rest slash something and this mapping is going to allow us to define what that something is this is going to give you the ability to create multiple apex rest classes behind the same endpoint URL that we expose and each apex rest class is then only going to listen to request meant for it to process on the other side you can forego the URL mapping and use a wildcard so if you want one main rest class that kind of act as a gatekeeper for your inbound traffic you can do this by replacing what you see in the screenshot ticket handler with just an asterisk wild card let’s see so exposing the class as a rest resource is going to require that the class is marked with a global access modifier as are the individual methods within and if we take a look at the method level take a note of how the methods are annotated within that HTTP annotation these are going to correspond with the various web service methods that Joshu Nami discussed previously they basically allow us to map a certain type of inbound request to a specific method within our class so in the screenshot you can see I have two main methods exposed here one is going to be for the handling of post requests and one for handling the puts these methods aren’t actually going to pass any data are going to be passed any data through parameters the method signatures are going to be blank and the methods are actually void so they won’t be returning anything either that’s going to leave us with a pretty big question to answer how exactly do we interact with that inbound request that the remote system is sending into Salesforce to get at that JSON payload – to begin processing it that’s where that rest context object is going to come into play it’s going to allow us access to that inbound request its headers in the request body and it’s actually going to be the object that we’re going to be populating with the response so after we’re done processing we can send something back to the wrote system in terms of like a simple message and an integer status code it could be as complex as you want it to be that the rest class can be used internally or externally and it is used externally you can use the standard authentication method or OAuth they get access to it if it’s used internally any of your apex code can’t can leverage it if you want to expose it externally and not use OAuth you could use other authentication methods or leave it completely wide open and for those scenarios you can actually connect that apex rest class to a Salesforce site it’s going to be much the same as when you expose a visualforce page where a series of visualforce pages to a Salesforce site but instead of assigning or exposing the visualforce page you’ll be exposing at the rest class that we create and of course you’re going to set up the public access settings with the required crud and FS FLS settings required by your phone analogy so the next thing we should do is take a look at the actual request and again it’s going to be a very simplistic JSON object that we’re going to send for this for this example you can see it’s a single object using the JSON format and in practice it’s not going to be uncommon free to receive arrays of objects with series of nested objects within it can get pretty complex pretty hairy very quickly so again keeping it simple our sample has a nice flat structure to it at a handful of data points that you can easily recognize as contacts in case little data points you know the first four or five here look like they have to do with a case and the last three the last name first name and email looks like they have to do with the contact we’ll see how we’re going to use those in a few moments so that’s the inbound requests that we received but what about the outbound message not outbound but a response that we send back to that calling system and so once we process that request we need to prepare a response and it’s going to be JSON formatted as well we’re going to use that container strategy that ami demonstrated earlier and within that container include two data data points one a response message as well as an integer response code at this point I’m going to jump over to dev console so we can take a deeper look into what that class looks like let’s double check that I’m still sharing my screen it looks like I am call me stop me if I’m not but what you should see on the screen right now is the dev console this is my inbound rest class so this is the class that I’m annotating with an at rest resource annotation meaning go ahead and expose

this class for some sort of inbound rest purposes you’ll see that actually do you have a URL mapping setup here so I will be accessing this externally via node Salesforce comm slash services slash apex rest slash ticket handler of course but they want to open that up and use this for all my inbound traffic I could use a wild card just like this instead of having the ticket handler as discussed both the class itself and the methods are going to be global they’ll be annotated with that HTTP POST or put or whichever web service that you want to assign to a specific method and here you can see that I basically have one method for the post one method for the point again no parameters accepted we’re not returning anything and both are actually going to use a common method for the processing of the request call a process request I’m going to pass process request a blob that’s going to be the response body and again how do I get the response body I’ll be using that rest context which gives me access to the request or the response and going through the request I have access to that request body which is all I really need so either way we go if we’re receiving a post or a put I’m going to funnel everything to this process request because one pattern that I like to use again if you’re not familiar with the web services but these common methods are post is going to be more along the lines of an insert where a point is going to be like an update well I can include additional logic in my common method here to look at some unique identifiers that that contact email address or the ID provided and perform some queries and that’s exactly what we’ll do so I’ll do the same processing whether it’s posts report but again your mileage may vary depending on what your use case actually is so looking at that common method again I’m going to pass to it a blob a response body that will be deserializing lady later right out of the gate I want to set up two properties just for for helping in the response generation bullying for whether it was a success or failure and some sort of message so if I encounter some sort of error I can provide some details back to that calling system I’m going to set them up in a very positive fashion I’m assuming that everything will you find but if not our try-catch blocks and other if-else branches are going to populate that accordingly so again just like Omni I demonstrated I’ll wrap everything in a try-catch just because we’re working with remote systems remote systems change all the time they may become unavailable let’s just account for the the unpredictable here so once we get into our try-catch block the first thing we’ll do is make sure we have a valid response body or at least a response body that looks like it can contain some JSON and if so we’re going to to do a type D serialization here so we’ll use the response body at the string version the the response body and D sterilize it into one of two of my inner classes one inner class which I have at the bottom here is going to contain the same exact data points that the inbound JSON is sending over to us again you can see points for the contact and then some data points for our case record I also have an a-class to be used for the generation of the response with those two data points the the response code as well as the message that will send back so we’ll look at that at the end of the method but just take note that I have two one for response one for what we receive inbound for the JSON so we can do that D serialization so ID sterilize into an instance of that class that we just looked at I’m going to call it request I’m going to set up two variables for the two s objects that we know we’re going to be working with at some point contact and a case and next big blocks that I have here actually deal with the contact and then the case they’re going to follow a very similar format where I’m going to check for some sort of unique identifier for contact it’s going to be a request email and for case it’s going to be a request ID if I do have one what I will do is I’ll query that object so for contact it’s going to be an email I’m going to try to do a quick query to find some matching contacts if I find one great I’m going to assign it to my property and use it going forward if I don’t find one for whatever reason I’m going to go ahead and instantiate and populate a new contact based off the details of the requests that we receive so I’m going to use that that dotted notation to get access to the first name the last name the email and at that point we should have a nice contact that whether it existed where we created it we can do some additional fancy processing whatever we need to do here and finally of course if we’ve made updates or creating new we can do an up cert on it so very much the same thing going on for the case ID we do the query we assign the results to our case object if we don’t we create a new one and populated with the details this time request description subject and type again we’ll have a case object to work with and we can do really anything we want off of that if you can do it in Apex you can do it here then we perform the up cert on the record if we inserted or updated it’s up to date and we’re going to skip over this part because this is going to happen asynchronously but assuming everything was fine what we do we’ve already set up

the response we’ve got details we have a new rest response and we’re going to pass to it our actual response details again we’re going to use that container approach that I made shown so we have an external response container and inside we’ll have both our our success integer and a string message I’ve got an if-else branch here that if we weren’t able to pull out a request body an inbound request body will provide back that it failed and you know the remote system must provide a valid request body if we caught in an exception I’ll do the same thing request body was invalid or I can include the the dist actress whatever I need to do to let that remote system know and at the end we go ahead and set up the response body again we use that container map and the remote system will receive that response so I’ll do with them and demonstration after this that actually shows that portion of it but that portion that I skipped over I thought it would be nice if we could go full circle and say we receive information from that remote system that remote ticketing system and maybe the agents over there didn’t necessarily provide a case type would be great if we could leverage what ami had demonstrated and use the Watson classifier to say hey I have a case that has this description Watson can you tell me what sort of case type this is and what I do is pass the case ID off to this asynchronous method called case type async and this uses one of on these recommendations at the end there to actually use the call-out equals true flag side of the true is asynchronous and what we do is pass it the case ID so this is going to spin off a new asynchronous process it has the case ID we do a quick query for that we check to make sure that we do have a case description and if so we’re going to use Army’s legwork that make call out method that he went over passed to it the description of the case get a response back and then we’re going to check that response to see if indeed we do get a type back from Watson if we do awesome we just update the case type committed to the database and now our case that previously didn’t have a type has a fairly well-informed type hopefully that is exactly the type that’s intended so we’ll see that as well the next part what I’d like to do is jump over to another web tool called workbench I feel like I’m always praising workbench here but if you’re not familiar with it the cloud-based tool that Salesforce provides that has a lot of capability anything from data loader to schema browser query builder you can execute anonymous apex it also has something very cool called the the rest Explorer so if you want to explore and kind of traverse the the Native ap is you can do so here or you can also ping your apex rest classes which is exactly what we’ll do so we’ll be sending in to our apex rest class a request again we’re going to be doing something like node salesforce comm slash services slash apex rest and I called that use the URL mapping of ticket handler if I used a wild-card I could really use anything here I could I could type in anything but because I specified the URL mapping equals ticket handler it has to end with ticket handler for the request body I’ll use that same exact request that we had on this slide deck again those five data points for the request the type I’m going to leave null I’m going to give it a subject a status I’ll pass in an ID it’s not going to be a valid ID so the result of our query won’t return any cases will be forced to create a new one it won’t have a type but it will have a description so we will call Watson and Watson will hopefully populate the type for us will also create a contact for that case first based off of my details so what I’m expecting to see when I hit execute is a response come back including our container letting us know is a two hundred and X success if I jump over here I should have cleared out all the contacts and cases in our demo org no contacts no case is great nothing up my sleeve when I hit execute it’ll make that call out from workbench into our apex rest class we get our response container back so on the outside response with inside two data points the detail our success message and that integer a 200 as we didn’t encounter any issues on this Salesforce ID if we refresh our contacts I should have a Newkirk’s def key contact and I do first name last name and email address and when i refresh cases i should have a new case and it matched the details it associated with the cut the contact that we just created the subject matches and look that I do have a plumbing type so use the description of this case my faucets are leaking to come up with the correct type and that well before I pass it back on – Josh what I want to quickly demonstrate is the the response handling if there was indeed in there so if we don’t provide a valid body we won’t get

a success response back let me backtrack need to provide at least something so we’ll just give it something empty the request received was not valid we didn’t get a 200 back and just to show that the URL mapping worked if we use a wild card we could put anything here but because we didn’t will get another notice that that that apex rest service does not exist so you do have to use the tick the the ticket handler URL mapping it is enforced so at this point I will pass back to Josh we talked about a lot of code he’s going to wrap things up by talking about how do we provide that coverage for the code alrighty thank you very much Kirk I want to try and get control back and there we go if everybody can’t see my screen which it’s a custom apex rust endpoint right now please let me know thank you Kirk and Amy first of all I want to say that once again what we’re trying to show you here is not just little code snippets as illustration but we’re really trying to show you production worthy code and both in Kirk and on these examples we’re seeing very common patterns that people are going to be using things like using apex apex classes to match the data types that can be easily serialized from JSON wrapping the functionality within container classes and being able to do things like log the interactions and give us custom feedback when it comes to the JSON responses and things like that so a great introduction slash deep dive into how we can use apex in the real world to handle Apex rust both inbound and outbound now we come to a question of how do I test all of this stuff we want you to be able to pull this into your production server but if you can’t get unit test coverage obviously that’s not going to happen now I’m going to caveat these next few slides because Kurt AMI and myself really wanted to be able to give you a more of a full section on unit testing however what we found was at that section in and of itself was about 30 to 40 minutes of material and so instead of trying to get too into the weeds of it what I want to do is actually kick it over to a couple of pieces of content from Kirk himself so Kirk had a dream for session at this last Dreamforce 2015 if you go to bitly web service testing session and remember that all bit ly links are key sensitive so capital W s T and s are necessary this is a great example of how to unit tasks your web services into Salesforce itself and he also has a blog post bitly Apex call out test blog and we’ll put these we’ll try and get these links either out to you around the chat or they will be in the recap if you come back to developers else force comm this is a great blog post about doing Apex call-outs and how to get unit test coverage with them so again this is it’s a fairly complicated topic however we’re going to pull into Q&A if you’ve got specific questions about testing please let us know we’ve got the experts right here to talk about it but before we get into the questions just if you know this is arm someone the questions that came up the panel do we have a trailhead module on that all this yes we do make trail head your next step and earn the apex integration badge run over to trailhead and you can find that either by going down to the keywords of Apex or I believe it is in the intermediate developer trail so go to trailhead salesforce.com and add earn your badge on all the stuff that I’m talking about here and please give us your feedback good positive otherwise just give us a shout out anything is great we do take feedback extremely seriously it helps us make our webinars more more effective down the road if you would like to see a webinar on unit testing specifically either for Apex rest or a whole webinar on maybe unit testing other aspects of Apex or another advanced topic on apex that you’re curious about but maybe you haven’t had a chance to deep dive into and see some real code about how to work give us all this feedback we really want to hear from you it really does help us make our jobs easier down the road and then finally we are going to take your questions at least up to the hour we will see if we actually might be a little bit past the hour Omni and Kirk and myself are okay with hanging around a little bit if necessary let me get to a few of the basic questions that we were getting to first one which is an extremely common question that I get when one should we

use rest versus soap API and this is you know this is a little outside of the topics that we’ve got right now since we’re focusing on rest but it’s a very common developer question so let’s let’s at least try to tackle it to a certain extent one thing is that we’re not going to be able to answer this necessarily decisively for you this is something that’s kind of a due diligence sort of thing what I have found is that for instance the REST API is very useful for mobile devices because extremely lightweight it’s also great if you’ve got a language like note or Ruby which is really good at handling HTTP and JSON and so you can talk to those endpoints directly soap on the other hand is great if you can consume a wisdom actually I apologize I think in our chat we we said ETL that should be a wisdom file which makes it very easy for c-sharp and Java programs to Taco soap or Java or SARS to talk to a soap endpoint um on me or Kirk do you guys any any other scenarios that you guys can think of which really call out to you like this is a great use case for rest versus so I think that X when you call from within Salesforce to outside it really depends of what’s available to you if the same source has both API and soap I would use so I’m in rest I mean it’s it’s a lot simpler to use you ever love more control over the request and the response now if you’re calling from outside of Salesforce into Salesforce because you have both how would you know always use rests it’s just that much simpler excellent another question and this comes up actually I want to kick one off really quickly this is going to be the super super fast answer however here when we develop on the Salesforce platform we do have a tendency to throw out a lot of jargon and abbreviations and just sort of assume that everybody’s following along we did get a question about what DML is Gmail stands for database manipulation language and it’s basically all the verbs that we use effects like insert update delete absurd in order to manipulate our language so when omni was talking about DML commits he was saying that there are specific orders of execution that you might have to do when it comes to operating against that data another question do you need to create a connected app for someone to read for example the API of the accounts URL that I was showing it in a previous slide so no this is a so it’s actually interesting so we’re talking about two different but very similar things the REST API itself just needs a valid session or access token that can be conferred through our normal low auth flow which doesn’t necessarily require a connected application what a connected app is for is if you want to declare a third party client which is going to use our identity service so if your third party client wants to call into our REST API and use for instance my credentials or obvious Prudential’s or curt credentials but you don’t want to handle our username password that’s where you’re going to want to create a connected application in order to access our REST API um here’s what I’m going to kick right over to you on me when actually Hannah had this question the back of my mind as well does the Watson capability integration the cost and actually give us a quick background on Watson itself which is a product from idea yeah sure so Watson is actually a collection of services you know the there’s actually quite a quite a few services that you can log into or use the one that we’ve been using for the demo is the natural language classifier again it basically takes a text and it kind of figures out what what most likely the class of that text now you have to set it up it actually actually have to train it that’s the word that they use training involves creating basically CBA CSV files that have examples for questions and texts and then from that depending on it so it kind of depends on how good your your training CSV is to for for the results and then once the Watson kind of figures that or trains itself it knows how to classify things as far as cost each one of these services does have a cost

however you can you know create an account you have to go to bluemix that comma believe if you do a google search on bluemix you’ll get there and if you so if you created a free account you can actually create a classifier you can actually use any of the other IP eyes for free to kind of set up and test and and so forth and then once you I want to make it production ready you can actually you know add a credit card and basically the the payment is per transaction and it’s some you know fraction of a cent per transaction so you know depending on on usage could get up there but I think it’s it’s very marginal cost it sounds like it’s pretty reasonable if you’re just trying for development site I think so and you know I think it’s it’s obviously depends you know how many calls you make and how many api’s you use and so forth I mean the endpoints and services and within Watson but you know I think it’s for the kind of interesting thoughts things that it does and and you can deal with with the services there it’s you know it’s pretty cool you know to otherwise you have to program for that and you know that would take even longer and more expensive so right gotcha gotcha okay moving on to uh we always want to Security’s one of our big watch words when it comes to Salesforce so we have the question using each yes with a username and password I hear though the rest api is not secured we comment on this so let me let me give kind of a quickly couched answer that I’ll kick it over to audience for some more details short version HTTP HTTP itself is here and everything that we have from an API point of view has to use HTTPS there is no non encrypted version of the API transactions when it comes to our platform and our API is whether or not there’s a public API out there that has a non encrypted version which may be completely insecure there’s another question when it comes to user name and password the storage of that username password obviously is something that any any developer needs to do a little bit of background check to see to make sure that they’re using that username password in a responsible way encrypting that encrypting it if necessary or swapping out for a pattern that doesn’t require it to be stored somewhere so the rest API is secure I think some of the patterns that you might have around using the REST API may or may not be as as secure as the other this is one of the big reasons why a lot of the time we have an OAuth flow where the users entering their username and password into you the web browser and know is actually necessarily storing username password but in API integrations we frequently have the scenario where we’re using like an API user that one user is the person who’s responsible or quote-unquote person responsible for making API calls and Hanalei the responses um I mean Kirk do you guys have any quick best practices that you can think of especially when it comes to a scenario like this where an OAuth flow it’s more headless so an OAuth flow might not be necessarily even a possibility like if we’re going to handle username passwords for API either calling into the platform or calling out anything that you can think of that people should know real quick just very well said but in those situations where auth doesn’t necessarily work out and you’re you’re exposing the apex resthouse out of the OAuth flow through like the s elsewhere site you have that additional level of protection of course you can do a sort of IP restrictions or you can you set up the public access to minimize the amount of data that is exposed add that element of the track abstraction through the design depending on which methods are available what you’re exposing if you can’t use OAuth and you’re rolling your own that that’s one way you can address that gotcha and I actually just got a tweet for a mr Richard Tuttle good time to call up main credentials feature of spring 15 so check out our new features in spring 15 thank you Richard Tuttle for that quick shout out there is also so is there a question there’s a question here on how to customize the URL instead of salesforce.com services where they slash your rel mapping I think Kirk that you kind of walked us through pretty much the extension of this either you can use a wild card which is going to be dropped off of Apex rest slash whatever or you can create you can use a combination of static text and wild cards to build out like you use ticket handler you could also use ticket handler slash asker to kind of make it your endpoint + wild card text that comes into it any other details about like how we can kind of customize that endpoint for people to

use yeah if you are using that wild card you always have access to the DES for your request URI so you can look at that string and parse accordingly to whatever the remote system is providing to you another level of customization from Salesforce we would be adding a domain adding a custom domain so that gets you a little bit closer to a fully customized URL you’ll still have that domain Salesforce Services rest you may run into issues if you’re trying to mask the URL using other sort of domain services when certificates get involved that can get hairy sometimes so one thing to look out for if you’re trying to kind of hide salesforce.com in your requests you may run into issues with HTTPS or certificates not being valid gotcha gotcha and I want to wrap a whole bunch we have actually about three or four different questions on on ooofff once again our identity services is probably something we could do a whole other webinar on what I really want to do here is actually point you to there is an excellent article by My Lai recently exculpate react mr. Pat Patterson aka meta daddy called digging deeper into OAuth on the Salesforce platform so when it comes to your questions about when can you use username password is bearer token by default all of those things look at the article digging deeper into OAuth it’s a relatively long article but it’s a great overview of ooofff on our platform and the specifics of how we can use it now we are rolling it past the hour I see many of you are still sticking with us but I think I want to wrap things up with one question that does seem to be coming up multiple times on the encourage and both of your demonstrations you were using a class called integration or and this class seemed to handle a lot of the basic utility functions like logging and checking data formats and things like that obviously we probably don’t have the ten minutes it would take to walk through the code itself but but let me guess to two questions you guys can take them in either order one can you give us a quick overview of the functionality that that kind of class has that you’re wrapping into that and also is there any code that you guys can share with us either in a gist or did have link or something that we can send out the it to the attendees later so I mean that that’s a whatever we have in that class is probably a you know we can have a few webinars to cover essentially normally we have an integration architecture that we use that includes an integration class and an integration core class two classes that kind of play together integration core basically has a lot of the the logging it has some delayed commits it has some of the authentication in the cases of more complex authentication like auth in case you know to handle you know refresh token situations and things like that delete commits in case that’s necessary so it has all kind of kind of support type methods to help with the with the integration and then the call-outs are generally more a lot more the code methods are a lot more generic so normally you would have a method that you actually send it or you you first instantiate the integration class specifically with with some kind of credentials that gets you the the general endpoint then the when you call a you want it to make a specific call out you actually you know send it what resources you want to use you send it you know any headers that you want to add specifically for that endpoint the body any other information that needs to be sent and then the integration method actually can kind of sort all that things that all these things are generically and and and and make the call out so it’s we don’t what we usually have is when I said that we have the integration architecture we usually basically take what we have and we kind of adapt it to a new integration so everything that so it’s not always exactly the same for this purpose we kind of you know took a lot of code out and just after the and you know again

like I said in my demo we kind of pulled we made it a little bit more specific not as generic just so it’s it’s easier to run through it then it’s like it’s it’s quite it’s quite involved so which we can do as a demo other webinars on that if there’s interested right but what you’re saying is that what we saw here today is really the implementation level stuff specific HTTP call-outs handling the JSON responses the things that are kind of unique when we say we’re going to do an apex call-out where as integration cores doing the grunt stuff it’s doing the more baseline stuff that you have the slide on other considerations it’s kind of handling those other considerations yeah definitely and and you know most of the time the business logic you know once you go through you know the the transaction was successful well first of all you set up the request the transaction was successful you DC realize that was successful the repeat the you get a response that that usually is not part of the integration architecture that’s what we usually do is we keep that outside of the integration itself to keep it generic and then the caller actually handles the the the response itself the business object that goes into what to do with the transaction and that’s why one of the reasons why we have you know you know these classes so you know we can refer to them you know you can use integration core methods outside of the class itself actually in this their code that you guys have publicly available that’s pertaining to this or any the topics we’re talking about anything for me to this session or every previous reinforced session yeah we have a few Dreamforce sections that that you know we ran on integration and they have some of this information and you know we have some some blog posts that that we can share excellently and those blog posts can easily found at CRM science not comically that’s correct CRM science comm click on the blog and I can get it and actually have some links to some past three and four sessions as well in the Dreamforce tab gotcha all right one last question there was some logging that we saw kind of the top level of what are your guys’s there’s many ways you can you can log these responses results you know whether something was successful or fail there’s not necessarily one right way but what’s your guys’s perfet preferred method of logging are you creating custom objects and tracking those are you trying to handle that through some kind of file creation or what what do you guys do so I can jump on this one we do use a lot of times a custom object to hold our API transactions we’ll call it this will be anything inbound or outbound including the requests the headers the body the response that’s received I think well the one big practice isn’t to ensure that you have various debug log levels included as well especially speaking from a the app exchange side where we’re creating app exchange apps that are either sync apps for making call also receiving inbound requests from other systems have a way to throttle down instead of logging everything log just the errors or log nothing at all introduce the debug log levels into your code that’s something that is handled within the integration core that that class that was brought up earlier in addition to that you obviously can generate a lot of traffic say someone installs it I think the the go to default for upon installation we’re set up is going to be at the error level but in case someone swaps it over to save debug we want to capture everything they leave it on for a few weeks you can generate quite a large number of records so have some sort of self cleanup process as well not just to remove them after X amount of days X amount of weeks but remove them from the recycle bin is I mean if you’re not using it within let’s say four weeks eight weeks whatever maybe let’s just do a hard delete on them and free up your customer space gotcha sounds great and great stuff gentlemen thank you very very much we’re going to go ahead and call that a wrap I want to want to also thank Lana our silent organizer who’s been making sure that everything’s been running smoothly and also obviously thank everybody for joining us today thanks for your attention and hopefully we’ll see you next time we have a fourth comm webinar I have a good day everybody