[Apex] How do I interact with web APIs and make HTTP requests in Apex?

To interact with web APIs and make HTTP requests in Apex, you can use the HttpRequest and HttpResponse classes provided by Salesforce. Here's a step-by-step guide to get you started:

  1. Create an instance of the HttpRequest class:
1HttpRequest httpRequest = new HttpRequest();
  1. Set the HTTP method (GET, POST, PUT, DELETE, etc.) and the endpoint URL:
  1. If required, set the request headers:
1httpRequest.setHeader('Content-Type', 'application/json');
2httpRequest.setHeader('Authorization', 'Bearer your_access_token');
  1. If sending data in the request body, set the request body:
1httpRequest.setBody('{"key": "value"}');
  1. Create an instance of the Http class and send the HTTP request:
1Http http = new Http();
2HttpResponse httpResponse = http.send(httpRequest);
  1. Check the response status code and handle the response:
1if (httpResponse.getStatusCode() == 200) {
2    String responseBody = httpResponse.getBody();
3    // Process the response data
4} else {
5    System.debug('HTTP request failed with status code: ' + httpResponse.getStatusCode());

This is a basic example of how to make an HTTP GET request. You can modify the method, headers, and body as per your requirement. Additionally, you can handle different response codes and parse the response data accordingly.

Remember to handle any exceptions that may be thrown during the HTTP request. You can use try-catch blocks to handle them gracefully.

Note: Before making HTTP requests, ensure that you have the necessary remote site settings configured in Salesforce to allow outbound calls to the API endpoint.