Apex Web Services and callouts

This article explains how to create the web services from Apex Code, and how to access external web services using Apex code directly from Force.com.

Introduction to Apex Web Services and Callouts

Apex methods in your apex code can be exposed as web services so that these services can be consumed by any REST client. Apex supports the ability to write Apex logic , which you can in turn expose to web services. This ability gives a way to external apps to invoke these Apex web services and execute business process workflows directly from the external app’s end.
The same can be performed the other way, i.e. you can invoke external web services from your Apex code. This invoking is called ”Callouts”, and are performed using SOAP and WSDL or HTTP services (RESTful Services).

Apex Web Services:

You can expose your Apex class methods as a REST or SOAP web service operations. By making your methods callable through the web, external applications can integrate with Salesforce to perform all type of operations like Add, Update, Delete etc to and from salesforce. What that means is that you can create custom web services to make your APEX methods available to complete APEX code.

Syntax
Enabling an Apex Method as a custom class in a matter of just few simple steps.
1. First, you would have to create an Apex class and define it as global. You can do that by adding ‘global’ access identifier to the class definition.

@RestResource(urlMapping='/Account/*')
    global class YourApexClass {
}

Using global access identifiers makes the class visible and accessible to all Apex Scripts in the whole org, because of which, the class is now not limited to the Apex code of the same application. The URL mapping is appended to the base endpoint to form the endpoint for your REST service.

2.The next step is to create Static and Webservice Apex methods using respective modifiers. In the code snippet below, the method is annotated with @HttpGet means it is invoked for a GET request.

@RestResource(urlMapping='/Account/*')
global class YourApexClass {
    @HttpGet
    webservice static Account YourApexMethod() {
        //add logic here......
    }
}

That's it. All the necessary web services would be provided to you by Force.com platform.
For a running live example that highlights “Apex Web Services”, checkout the link below:
https://developer.salesforce.com/trailhead/en/apex_integration_services/apex_integration_webservices

Apex Callouts:

As highlighted earlier, Apex Web Services enables an external application to access Apex methods, and Apex Callouts provides Apex methods to access an external web service. This is especially useful if you have to integrate your SFDC org with third party web services like Google, Youtube, Facebook or any other external web service.

Authorize Endpoint Addresses
Before making a callout to an external site you will have to make sure that it is authorized. You can’t have code calling out any un-authorized endpoint. Before working with callouts, you will have to update the list of approved sites for your org on the Remote Site Settings page of your org. To know how to authorize the endpoints in your org, refer to the below link.

https://developer.salesforce.com/trailhead/force_com_dev_intermediate/apex_integration_services/apex_integration_callouts

REST callouts are based on HTTP. Each callout request is associated with an HTTP method and an endpoint. The simplest request is a GET request (GET is an HTTP method). A GET request is the request initiated by the sender to obtain some information about a resource utilized or saved in the server. When the server receives and processes this request, it returns the requested information to the recipient. With a callout, the result is the response object.

The common HTTP methods that can be used for rest callouts are:

  • GET
  • POST
  • DELETE
  • PUT

The below code snippets explain the use of GET and POST methods.

Get Data

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
    // Deserialize the JSON string into collections of primitive data types.
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    // Cast the values in the 'animals' key as a list
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for (Object animal: animals) {
        System.debug(animal);
    }
}

Post Data

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Set the body as a JSON object
request.setBody('{"name":"mighty moose"}');

HttpResponse response = http.send(request);

// Parse the JSON response
if (response.getStatusCode() != 201) {
    System.debug('The status code returned was not expected: ' +
    response.getStatusCode() + ' ' + response.getStatus());
} else {
    System.debug(response.getBody());
}

When making a callout from a method, the method waits for the external service to send back the callout response before executing the subsequent lines of code. You can also place the callout code in an asynchronous method that’s annotated with @future. This ways, the callout will run on a separate thread, and the execution of the calling method isn’t blocked.

Responses

  1. Hi Jogender, this is an amazing article, it helped me a lot. Thanks for sharing.

Comments are closed.

Popular Salesforce Blogs