Here's Apex code for an @HttpPost web service in Salesforce. This code defines a simple web service that accepts JSON data through an HTTP POST request and returns a response.
@RestResource(urlMapping='/myservice')
global with sharing class MyRestService {
@HttpPost
global static String doPost(String requestBody) {
try {
// Parse the incoming JSON request body
Map<String, Object> requestMap = (Map<String, Object>) JSON.deserializeUntyped(requestBody);
// Process the data as needed
String firstName = (String) requestMap.get('firstName');
String lastName = (String) requestMap.get('lastName');
Integer age = (Integer) requestMap.get('age');
// Create a response JSON
Map<String, Object> responseMap = new Map<String, Object>();
responseMap.put('message', 'Data received successfully');
responseMap.put('firstName', firstName);
responseMap.put('lastName', lastName);
responseMap.put('age', age);
// Serialize the response to JSON
String responseJson = JSON.serialize(responseMap);
return responseJson;
} catch (Exception e) {
// Handle any errors
Map<String, Object> errorResponse = new Map<String, Object>();
errorResponse.put('error', 'An error occurred: ' + e.getMessage());
return JSON.serialize(errorResponse);
}
}
}
In this example:
- The @RestResource annotation defines the URL mapping for the web service.
- The @HttpPost annotation specifies that this method should be invoked for HTTP POST requests.
- The doPost method takes the JSON request body as a string parameter and processes it.
- The request body is deserialized into a map for processing.
- The processed data is used to create a response map.
- The response map is serialized back into JSON, which is returned as the HTTP response.