Diving into HTTP Methods GET and POST with Apex in Salesforce
What is HTTP ?
HTTP (Hypertext Transfer Protocol) is a communication protocol that enables information exchange on the World Wide Web. Many transactions on the Internet are carried out via the HTTP protocol. HTTP is based on a client-server model, meaning that a client (usually a web browser) makes a request to a server (usually a web server), and the server processes the request and sends back the response.
- HTTP (Hyper-Text Transfer Protocol) is an application-level communication protocol for hypermedia information systems distributed from a source and available for public use.
- They determine the rules for data flow between the client and the server.
- Generally, web pages contain text, images, videos, etc. It is used to transmit various content such as.
HTTP methods include methods such as GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS. Each method is used for different functions and follows specific HTTP directives (RFC standards). For example, the PUT method is used to update a resource, while the DELETE method is used to delete a resource.
In this article, we will examine the GET and POST methods.
Understanding the Data Model
The data model of our work is like this. We see the areas of the Event and Participant objects, fields and their relationship with each other in the visual.
In this study, we will only deal with the Event object.
HTTP GET Method
GET method is a frequently used method in the HTTP protocol. Its function is to retrieve a specified resource. A GET request is generally used to retrieve data from the server and does not contain a request body. Instead, a URI (Uniform Resource Identifier) is sent that identifies the requested resource.
- Get method only retrieve data.
- Parameters in headers & URL in Get method.
- Get method does not have a request body.
- Get method can be called many times.
/**
* Created by Yusuf.Acar on 22/04/2024.
*/
@RestResource(UrlMapping='/v2/event-meetings/*')
global class EventRestService2 {
public static final String NO_RECORDS_FOUND = 'No Records Found';
public static final String LIST_HAS_NO_ROWS = 'List has no rows';
public static final String INVALID_ID = 'Invalid id';
public static final String REQUIRED_FIELD_MISSING = 'REQUIRED_FIELD_MISSING';
public static final String CANNOT_DESERIALIZE_INSTANCE = 'Cannot deserialize instance';
public static final String EVENT_CREATED = 'Event is created';
public static String recordId ;
public static Event__c newEvent;
public static Event__c event;
public static RestRequest request = RestContext.request;
public static RestResponse response = RestContext.response;
public static Map<String, Object> responseBody = new Map<String, Object>();
@HttpGet
global static void getEvents() {
System.debug('getEvents method is start ');
try {
//Send data in JSON format. Otherwise, the data goes as text format.
response.addHeader('Content-Type', 'application/json');
//Get path variable from Endpoint after '/event-meetings/' section
recordId = request.requestURI.substringAfter('/event-meetings/');
//Event__c SOQL by Salesforce Record Id
event = new EventsSelector().selectEventById(recordId);
setSuccessfulGETResponse(event.Id, event.Name, event.EventType__c, event.EventStartTime__c, event.EventEndTime__c);
} catch (Exception error) {
//Call errorHandler method and get a filled response
System.debug('error: '+error.getMessage());
setUnsuccessfulGETResponse(error.getMessage());
}
System.debug('getEvents method is end ');
}
//GET Method Successful Response
private static void setSuccessfulGETResponse(String eventId, String eventName, String eventType, Datetime eventStartTime, Datetime eventEndTime) {
responseBody.put('eventId', eventId);
responseBody.put('eventName', eventName);
responseBody.put('eventType', eventType);
responseBody.put('eventStartTime', eventStartTime);
responseBody.put('eventEndTime', eventEndTime);
response.responseBody = Blob.valueOf(JSON.serialize(responseBody));
}
//GET Method Unsuccessful Response
private static void setUnsuccessfulGETResponse(String message) {
if (message.containsIgnoreCase(NO_RECORDS_FOUND) || message.containsIgnoreCase(LIST_HAS_NO_ROWS)) {
responseBody.put('error', message);
response.statusCode = 404;
} else if (message.containsIgnoreCase(INVALID_ID)) {
responseBody.put('error', message);
response.statusCode = 400;
} else {
responseBody.put('error', message);
response.statusCode = 500;
}
response.responseBody = Blob.valueOf(JSON.serialize(responseBody));
}
}
Example Http Snippet :
GET /services/apexrest/v2/event-meetings/:recordId HTTP/1.1
Host: sfa-yacar-training-9a-dev-ed.my.salesforce.com
Authorization: Bearer {{token}}
Cookie: BrowserId=tjzd5aDVEe6BDNnTYBncIg; CookieConsentPolicy=0:1; LSKey-c$CookieConsentPolicy=0:1
- For successful GET method transactions, We return a response body containing account information and the “200 OK” Response Code.
- For unsuccessful GET method transactions, We return the “404 Not Found” Response Code and error message in the response body.
HTTP POST Method
The HTTP POST method is an HTTP method that a client uses to send data to a server. This method is typically used to pass user-supplied data to a server via a web form, but can also be used to send data via APIs.
The post method is mostly used for these operations :
- Posting a message to a bulletin board, newsgroup, mailing list.
- Adding a new user through a signup modal.
- Extending a database through an append operation.
- Providing a block of data, such as the result of submitting a form, to a data-handling process.
/**
* Created by Yusuf.Acar on 22/04/2024.
*/
@RestResource(UrlMapping='/v2/event-meetings/*')
global class EventRestService2 {
public static final String NO_RECORDS_FOUND = 'No Records Found';
public static final String LIST_HAS_NO_ROWS = 'List has no rows';
public static final String INVALID_ID = 'Invalid id';
public static final String REQUIRED_FIELD_MISSING = 'REQUIRED_FIELD_MISSING';
public static final String CANNOT_DESERIALIZE_INSTANCE = 'Cannot deserialize instance';
public static final String EVENT_CREATED = 'Event is created';
public static String recordId ;
public static Event__c newEvent;
public static Event__c event;
public static RestRequest request = RestContext.request;
public static RestResponse response = RestContext.response;
public static Map<String, Object> responseBody = new Map<String, Object>();
@HttpPost
global static void createEvent() {
System.debug('createEvent method is start ');
try {
//Send data in JSON format. Otherwise, the data goes as text format.
response.addHeader('Content-Type', 'application/json');
createEventHelper(request);
setSuccessfulPOSTResponse(EVENT_CREATED, newEvent.Id);
} catch (Exception error) {
System.debug('error : ' + error.getMessage());
System.debug('error line : ' + error.getLineNumber());
setUnsuccessfulPOSTResponse(error.getMessage());
}
System.debug('createEvent method is end ');
}
//POST Helper Method Inserting Event
private static void createEventHelper(RestRequest request) {
newEvent = (Event__c) JSON.deserialize(request.requestBody.toString(), Event__c.class);
insert newEvent;
}
//POST Method Successful Response
private static void setSuccessfulPOSTResponse(String message, String eventId) {
responseBody.put('Id', eventId);
responseBody.put('message', message);
response.statusCode = 201;
response.responseBody = Blob.valueOf(JSON.serialize(responseBody));
}
//POST Method Unsuccessful Response
private static void setUnsuccessfulPOSTResponse(String message) {
if (message.contains(REQUIRED_FIELD_MISSING) || message.contains(CANNOT_DESERIALIZE_INSTANCE)) {
responseBody.put('error', message);
RestContext.response.statusCode = 400;
} else {
responseBody.put('error', message);
response.statusCode = 500;
}
response.responseBody = Blob.valueOf(JSON.serialize(responseBody));
}
}
- POST method creates new data.
- Parameters in body, headers & URL in POST method.
- POST method has a request body.
- POST method creates new data every time it is called.
Example HTTP Snippet :
POST /services/apexrest/v2/event-meetings HTTP/1.1
Host: sfa-yacar-training-9a-dev-ed.my.salesforce.com
Content-Type: application/json
Authorization: Bearer {{token}}
Cookie: BrowserId=tjzz4aDVEe8BdNnKTBnbIg; CookieConsentPolicy=0:1; LSKey-c$CookieConsentPolicy=0:1
Content-Length: 250
{
“Name”:”Galatasaray — Fenerbahçe Futbol Müsabakası”,
“EventType__c”:”FootballMatch”,
“EventStartTime__c”: “2024–05–19T16:00:00”,
“EventEndTime__c”:”2024–05–19T18:30:00",
“City__c” :”İstanbul”,
“Venue__c”:”RAMS Park”
}
- For successful POST method transactions, We return a response body containing account information and the “201 Created” Response Code.
- For unsuccessful POST method transactions, We return the “400 Bad Request” and “500 Internal Server Error” Response Code and error message in the response body.
Summary
In this article, We created GET and POST methods using REST Integration and using them, We were able to create new records in Salesforce and access these records with Postman tool.
In our next articles, We will discuss other methods and the working structure of the postman tool in more detail.
Thank you for reading, please like or share to support. You can share your thoughts with me. I’m looking forward to your feedback! I would love to connect with you at LinkedIn.