Salesforce Integration API

¡Supera tus tareas y exámenes ahora con Quizwiz!

Get/POST.PUT.PATCH.DELETE

(This structure is always the same:) Http http = new Http(); HttpRequest request = new HttpRequest(); resquest.setEndpoint('https://jsonplaceholder.typicode.com/todos'); request.setMethod('Get); HttpResponse response = http.send(request); 55 Min into 9/14 class integration good example... UPS driver

Status Codes

*when you send a request using POST, PUT, GET, PATCH, DELETE the application server is going to send you a response code back and this will acknowledge what action was taken if any at all. 1xx: Your request has been received successfully, but it is still in progress 2xx: It gives you success messages 3xx: Your request is good/ accurate but need additional information 4xx: You made a bad request 5xx: Server related issue 200: It is ok 201: Created 204: No content - you no longer have the data such as Deleted content 400: Bad request 401: Not Authorized 404: Not Found, whatever you were looking for does not exist

create class with salesforce console (API)

// https://techproed51-dev-ed.my.salesforce.com/services/apexrest/contacts/ // @RestResource(UrlMapping='/contacts/' global class RestApiContactServiceProvider { // Create a service request method to read all contact information // this means they can only read data w/ this method request @httpGet @HttpGet global static List<Contact> getContactService(){ List<Contact> contacts = [SELECT id, FirstName, LastName, Phone, Email FROM Contact LIMIT 50]; return contacts;

API? What do you need when you want to create records using API? Swagger document: What type of language is the structure of API? How to you gain access to API? What website do you use for API?

1. Helps comminication between applications 2. Endpoint. 3. Body Structure 4. JSON 5. Authorization token 6. Postman (All Companies are using to do API manipulation)

@future annotation

@future(callout=true) // @future system knows you are going to use this //structure somewhere else so you can not have a return //type it knows you do not need any data. public static void createRoomDate() { // if you want it to be public when creating new record if you do not have the @future(callout=true) this is the error you will get in image @future(callout=true) goes on top of the method.

REST API vs SOAP API

APEX Person person = (); person.firstname = 'Talha'; person. lastname = 'Kaya'; person.id = 61; JAVA Person person = (); person.firstname = "Talha"; person. lastname = "Kaya": person.id = 61; JSON { "firstname" : "Talha", "lastname" : "Kaya", "Id" : 61; } XML <firstname> Talha <firstname> <lastname> kaya <lastname> <Id> 61 <id>

Process start to finish we will create it and see it on other applications.

API : Communication between applications --------------------------------- REST VS SOAP API Faster : More Secure Uses more Formats : Uses only XML --------------------------------- Request => <= Response endpoint / url What do we have in the endpoint?Rest vs SOAP => Base URL + path params + ? query params GET: read the data POST: create data PUT: update records DELETE: delete records How do we understand that our request has been successful or not? - check with status codes: Status Codes: 200 - ok 201 - created 202 - accepted 400 - Bad request - need to give the right swaggar documentation. 401 - Not authorized - 404 - Not Found GET and DELETE - no need for data/ body - this means that you do not need to send data along with them. POST and PUT -we need body (data) - we need to send data along with them. Authentication vs Authorization General Access- authentication Specific Access- Authorization my patient and admin has authentication admin has both - Authorization to get into records which object helps us send the object to the client? we create the HTTP object to be able to communicate within Salesforce. - if you use this @future annotation then you can not return values / data. @future(callout=true) public static void createRoomData(){ Http http = new Http() HttpRequest request = new HttpRequest(); - this request keeps our secrets - keeps our request method - tokens request.setEndpoint('https://medunna.com/api/users'); - Url for our application request.setMethod('GET'); - we are going to set this method to read the data or we can use: request.setMethod('POST'); - we are going to set this method to create new record or update the data request.setHeader('Authorization', 'Bearer token'); - if this is a private application you need a header request.setHeader('Content-Type', 'application/json'); - whatever format you're going to be using for your data you need to put them in the header. - for example if you are going to use JSON you will use this like the above example. - if you have authorization token you need to put them in the header, or API key => provide them in header request.setHeader('Authorization', 'Bearer token') ----------------------------- if you are sending a POST request do you need to consider the format you are going to send the data? yes request.setHeader('Content-Type', 'application/json') or ('application/xml') - whatever language you are going to use ----------------------------- we also need to set the body because we are sending a request and I need to share my data so I'm going to say... => request.setBody('data'); - *all of the above code is in the HTTP request object saved and sending to the client. when you send this to the client who is the object that will receive the response and store it into itself? HTTP response object -> below ------------------------------------------------------------ HttpResponse response = http.send(request); - who is responsible for sending and receiving requests? HTTP - so it will be the same as request object only using response. - this is where HTTP will say send my request ------------------------------------------------------------ System.assert(response.getStatusCode()==201); when you are creating endpoints then other clients can use the endpoint and send requests to us.

What is an API stand for for?

Communication between applications. + Application Programming Interface: - Middle man between the Application/ UI (user interface) and the database, and other application such as Amazon or somthing like that. secure data do transactions faster Postman is a website that supports API

Developers

Create structure of API body

HTTP object => to connect with Salesforce

Http http = new Http(); HttpRequest request = new HttpRequest(); -Http communicates with other applications using internet -this sends the request and gets the response -can send to remote applications and give you response back.

HTTP

HttpRequest who stores response from HTTP? - Http Response Serialization vs deserialization Remote Site Settings Add new remote site name: any name url: Base URL Save API integration on Salesforce application

why do we asynchronous?

In order to allow the callout which means API's from triggers do we need asynchronous or will salesforce help us to do this process already? - we use asynchronous because trigger itself cannot support callouts. You will get an error message when you try to trigger them from triggers. in this case we will use @future method which is an asynchronous method. use below code for this.. @future(callout=true)

REST API

JSON, XML, TEXT, HTML, JS - faster - HTTP = representational state transfer -REST is more important to understand HTTP Methods Get: read Post: create Put: update(full) Patch: update(partial) Delete: delete

Are we responsible for API end points creation or Are we responsible for API manipulations? @RestResource? what does this mean? @HttpGet? What does this mean?

Mostly responsible for creating endpoints for example - payments. We are also responsible for testing and validating endpoints. When you are told to create an endpoint: - I need to have API contact information using API to read, create, update and delete the data. * If we need to create a class for this as an endpoint what is the class annotation we need to use @RestResource What this does is it creates URL mapping and it maps our API to the URL below /contacts will be added onto the end of the url so we can design what the contacts structure. Example: hh..salesforce.com/services/apexrest/contacts/ @RestResource(URLMapping= '/contacts/' ) -------------------- @HttpGet when the client gets the request they will only read the data. They can read multiple contact data --------------------- @HttpPost @HttpDelete @HttpPut

SOAP API

Only supports XML - Slower - HTTPS - more secure

Request => Response

Post request => You want to create records in the system Put Request => You want to make updates in the system Patch Request => You want to make a partial updates in the system. Get Request => You want to read data from the system Delete => You want to delete records in the system

API Structure

REST API SOAP API

Connecting API to Salesforce

Remote Site Settings => new Remote Site => then put new name => copy and paste the site we are getting API from.

when you go into test your code from slide 41

RoomPostResquestTriggering.postRoom( ); when you type this code it creates the record and if you send the same exact code you created it will give an error because 2 records cannot have the same ID. if you want to make a different record you can go to description give a different description with the reason 'instructors updates'

Serialization vs deserialization. (Interview question)

Serialization: converting APEX object data to JSON Deserialization: -Converting JSON data to APEXObject -you are going to need this the most

Public Class RoomPutRequest{ public static void putRoom{

String dataToUpdate = '{ "id": 10, "username": "theUser", "firstName": "John", "lastName": "James", "email": "[email protected]", "password": "12345", "phone": "12345", "userStatus": 1 }' Http http = new Http(); HttpRequest request = new HttpRequest(); request.setEndpoint = ('https://medunna.com/api/rooms'); request.setMethod('PUT); request.setHeader('Authorization', 'Bearer *encryption Key request.setBody(dataToUpdate); request.setHeader('Content-Type', 'Application/json'); HttpResponse response = http.send(request); System.assert(200 == response.getStatusCode(), 'Status code is not Matching! ' +response.getStatusCode() ); ') } } ---------------------------------------------------- NEXT STEP is to: to call this method and send to the website you need to execute the code via the developer console in salesforce and execute highlighted ... call the class with: RoomPutRequest.putRoom( ); // this will send to the website and if you open up the log it will give you the 201 message (success). ----------------------------------------------------------------- note* with PUT requests you need to put the body. we are creating rooms for a hotel in this example so we can go to swagger documents for reference. - api/rooms (update rooms) structure of body JSON copy and paste into console remember that with the PUT request you need to include the id of the room that you are going to update. - once you created the new record that you are going to update you create a new String and add it into the code block above. String dataToUpdate = '{ "id": 10, "username": "theUser", "firstName": "John", "lastName": "James", "email": "[email protected]", "password": "12345", "phone": "12345", "userStatus": 1 }' 37.22 Min into session 5 - 9/18

What types of objects do you have in APEX programming language objects

String- Integer- Long- Decimal- Boolean- Map- Lists- Array- Set- ----------------------- Dont have these object.... Room: Todo so what do you do? Create Custom Objects -------------------------- ***all the child classes of Object (Super class)*** subclasses

Swagger vs Postman

Swagger is mostly used for the documentation. Swagger is limited to the options for API manipulation. Postman has more detailed structure and you can keep all swagger documentation in the app. - you can customize your parameters with Postman.

what kind of methods can you use to convert from APEX to JSON and from JSON to APEX?

This process is called serialization and deserialization. For deserialization: methods you can use= - deserializeUntyped - serialize HTTP (delivery person) - HttpRequest GET setMethod setHeader('Authorization', 'Token') setEndpoint POST / PUT / PATCH setMethod setHeader('Authorization', 'Token') setEndpoint setBody(data) setHeader('Content-Type', 'application/json')

@RestResource(UrlMapping='/contacts/') What will the URL look like??

URL: //salesforce.com/services/apexrest/contacts/ Using rest API This is the way we create the service provider class.

URL- As a whole is called API= Base + Path Parameter + Query Parameter = API

Uniform Resource Locator https://Amazon.com = Base URL -------------------------------------------- https://Amazon.com/api/products = Path Parameters (products) => https://Amazon.com + path parameter --------------------------------------------- { name : camera price : 500 id : 1000 } { name : microphone price : 100 id : 1001 } { name : TV price : 800 id : 1002 } name='Camera'&price=500 --------------------------------------------------- https://amazon.com/api/products?price < 100 after ? is called = query parameters

SalesForce token (security)

Using Bearer Authentication: This is updated every 24 hours. Admin token: Patient token if you are not part of the system you will get no token.

when are we going to use After Insert? Example

We create a new contact in the admin side. Once this is created it creates a record. After this is done the trigger sets (after insert) this trigger takes the user ID from the database of Salesforce which means we will use SOQL then we will send the information to the client application.

Integration recap

What is integration? - it is API. Application Programming Interface When do you need to use API and what do you need to use with API? - you might have to use triggers meaning that you might need to do multiple actions at the same time. - this can be used for the approval process, emailing process, communications process, it can be any process w/ communication between multiple applications. What do you need to do this? - you do the actions on the admin side and then set up your triggers (this will do multiple related actions at the same time) contact: name: John LastName: Case, 7896557233, email: [email protected] SOQL: we will get the information from Database Then we will use Asynchronous to enable API along with triggers. you can use @future API: will send the information to client companies/ applications

How does API effect Salesforce Apps?

When you create your admin records records going to API then records are updated in the Database your application interacts with other API Limit users with API Son, go to neighbor and ask for sugar = Request Neighbor gives you sugar = Response REST VS SOAP API

Postman

Workspace => HTTP => New => GET (untitled request) (action 2) => URL (action 1) => Send (action 3)

Swagger document

You can find your API structure info see bookmarks

Serialization / Deserialization

for example in Salesforce we are writing our code in Apex and when we are writing our API we are writing it in JSON. in order for salesforce to understand and vice versa you need to understand these two concepts. What is this code accomplishing? We are sending a Post request to the website medunna.com for a TWIN room, Price, Room Status, RoomNumber, Description. Json to Apex : deserialization Apex to Json : serialization see in class slide 39 for where this goes in the api code Room room = new Room( ); room.description = 'description'; room.price = '750'; room.Number = 332740; room.Type = 'TWIN'; (needs to match exactly with application) room.status = true; String json = JSON.serialize(room); HttpRequest request = new HttpRequest( ); request.setBody(json); http.send(request); HttpResponse response = http.send(request); (- is going to get my object. ) System.assert(response.getStatusCode( ) == 201, 'The status code does not match')

Authorization Vs Authentication

for example: 6 appartement building complex... 6 families have permission to access the building - Authentication is a general access Can apartment 1 have access to apartment 4? - NO - Authorization is a specific access ======================================================= now lets look at it from a Salesforce example ======================================================= -Hospital- The patients have authentication to get into the hospital but do not have authorization to the systems. - The Admin has both authorization and authentication in the system. Admin: Name: Tom lastname: admin id 101 Patient name: patient lastname: Case id: 102

deserialized untyped

for regular Apex objects existing- already an object and salesforce knows what type of object it is. custom objects need to be typed because APEX does not know what the object is.

Invalid session ID

go to Salesforce console and System.debug('System.UserInfo.getSessionId().substring(15)); This will give you your Bearer token information

how do you find the bearer token?

go to the application website right click and inspect page go to application in the session storage click on the link this will populate a Key and Value copy the token which is the value you will take the value and place it after 'Bearer token-ejyhbGci01'

https://Amazon.com/api/products

https://Amazon.com/api/customers https://Amazon.com/api/patients https://Amazon.com/api/users https://Amazon.com/api/doctors https://Amazon.com/api/admin this is 5 different endpoints... customers patients users doctors admin

When we do api manipulation, we can use 2 things for validation:

important** examples given with Postman... if you are going to do a POST request this will be user id, title will be this Status code=> to make sure the request is good or not Data(body) => does the request have a body? key, value - if yes then record is good... and API endpoint are good - if no then record does not exist... then no endpoint such as: (this is the structure of an API endpoint) [ { "userId" : 1 "title" : "Do you like this shirt" "id" : 1000 } ] --------------------------------- Post Request - you need to send data Put Request- you need to send data when you are using get and delete request : No Body required when you are using POST and PUT request the body is required. (PATCH) - changing data so you need body. If you are going to use Query Parameters

How do you integrate into your application? you will use @future because once the record is created

public class MedunnaRegistration{ @future(callout=true) public static void registerUser(String contactId){ List<Contact> contacts [SELECT FirstName, LastName, Email, Phone,MobilePhone FROM Contact WHERE id=:contactId]; String data = '{"email":"[email protected]","firstName":"amadou","langKey":"en","lastName","diallo","login":"amadouser123","password":"22345323$","ssn":"222-33-5644"}; Http http = new Http( ); request.setEndpoint('https://medunna.com/api/register'); request.setMethod('POST'); request.setHeader('Content-Type', 'application/json'); request.setBody(data); HttpResponse response = http.send(request); System.debug('message: ' + response.getStatusCode( ) ); } } register the applicant with website with: MedunnaRegistration.registerUser( ); => this creates the object and sends the request. (create the object) in developer console. --------------------------------------------- Lets create a contact trigger (after insert) that retrieves the contact id when MedunnaRegistration.registerUser( ) creates a new registration trigger ContactTrigger on Contact(after insert){ String id; for(Contact contact : Trigger.new){ id = contact.Id; } MedunnaRegistration. registerUser(id); } //since id is outside of the method then we have to use it as //a parameter in the registerUser( ) // this will pull the contact id and we will use an SOQL query to pull the data into our database for the information we need.

Creating API in SalesForce

public class RoomGetcallout01 { public static void getRoom(){ Http http = new Http(); // This object helps us for the delivery of the request HttpRequest request = new HttpRequest(); // this object gets your endpoint and request method type(Get, post, put, delete) and then saves them] // // // Send the get request for the 6th todo object and get the data // https://jsonplaceholder.typicode.com/todos/6 request.setEndpoint('https://jsonplaceholder.typicode.com/todos/6'); // We are setting the endpoint/ url request.setMethod('GET'); // Set the method for Get request HttpResponse response = http.send(request); JSON.deserializeUntyped(response.getBody()); Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(response.getBody()); }

public class RoomGetCallout{

public static void getRoom( ){ Http http = new Http( ); // API callout we just manipulate the data // We are just doing data manipulations for other client //application. // Am I using existing endpoint? or am I creating new for example ==> Swaggar documentation - if we have the existing documentation then we are performing a callout which means I am doing an API manipulation. if you want to read data from PostMan, you want to create some records into your SF system using Postman We need to create communication endpoints for clients. If we want to to create our specific endpoints on top of our class what annotation are we using? => @RestResource(UrlMapping='account') if an application wants to send us a GET request what do we use? -@HttpGet If they want to send post request if they want to create records into our system what would they use? -@HttpPost request If they want to do updates on our existing records what would you use? -@HttpPut if you want to delete records - @HttpDelete this is about service provider. callout means api manipulation => (Get, Post, Put, Delete) for callout callout are we creating or pulling out of existing records - existing records (swaggar) - use

Create Trigger to trigger slide 41

trigger AccountTrigger on Account (before insert){ for(Account w : Trigger.new){ if (w.Name.equals('TechProEd')){ w.addError('TechProEd Cannot be an account name!'); }else{ w.Industry = 'Agriculture'; } RoomPostRequestTriggering.postRoom( w.Name); }

custom object (this is how custom objects are converted from the API to an object in salesforce. Last hour of (9/14/2022 class)

you need to give the type - JSON. deserialize(response.getBody(), Todo.class) todo.class is the custom object. we created in the todo class. from the body() put it into the todo class everything will be returned as an object so we need to convert to a smaller data type than object which will be whatever we created (string, int, map) whatever it is for the class you created. what you need to do is CAST the data type to the object where you are storing your data. so you will cast it to the Todo Object...

create class for RoomPostRequestTriggering{ }

{ @future(callout=true) public static void postRoom( String accName){ Account acc = [SELECT Name FROM Account WHERE Name = :accName]; //what do we need in this method? //what is the objects that is going to take the endpoint, //token, JSON, data? Http http = new Http( ); Room room = new Room( ); room.description = acc.Name; // this is pulled in from SF UI room.price = '750'; room.Type = 'TWIN'; (needs to match exactly with application) room.Number = 332740; HttpRequest request = new HttpRequest( ); // if you want to create a room what do you use? // this is the endpoint in arguments below // this is how we make our request request.setEndpoint('https://medunna.com/api/rooms'); //What type of request are we sending to the client //application? request.setMethod('POST'); // (key,Value) argument below request.setHeader('Authorization', 'Bearer token-ejyhbGci01'); // this will say I know who you are. //what will be the application content type? ('Content, value) request.setHeader('Content-Type, 'application/json'); //We need to send the body and serialization } // Need to create a room object public class Room{ public String description; public String price; public Integer roomNumber; public String roomType; public Boolean status; }


Conjuntos de estudio relacionados

HG&D chapter 3 likely test questions

View Set

Business 101 Test 2 Ch. 8,11,12,13

View Set

Four Essential Features of A State

View Set

Managing and behavior organization

View Set

Questions and Notes - Chapter 20

View Set