How do you write an Apex REST endpoint that handles both GET and POST?
Suggested answer
Example structure: @RestResource(urlMapping='/orders/*') global with sharing class OrderAPI { @HttpGet global static OrderResponse doGet() { String orderId = RestContext.request.requestURI.substringAfterLast('/'); Order__c order = [SELECT Id, Name FROM Order__c WHERE Id = :orderId WITH SECURITY_ENFORCED]; return new OrderResponse(order); } @HttpPost global static Id doPost() { String body = RestContext.request.requestBody.toString(); OrderRequest req = (OrderRequest) JSON.deserialize(body, OrderRequest.class); Order__c o = new Order__c(Name__c = req.name); insert o; RestContext.response.statusCode = 201; return o.Id; } } Best practices: use WITH SECURITY_ENFORCED in queries, return structured wrapper classes, set appropriate HTTP status codes (200, 201, 400, 404), handle exceptions and set RestContext.response.statusCode to error codes with error body.
Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.
Community comments (0)
No comments yet.
Sign in or create a free account to add a comment. Comments are moderated before they appear.