How do you implement and test an Apex HTTP callout?
Suggested answer
Implementation: Use HttpRequest and HttpResponse classes with an Http instance:
Http h = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint('callout:MyNC/api/v1/resource'); req.setMethod('POST'); req.setHeader('Content-Type', 'application/json'); req.setBody(JSON.serialize(payload)); req.setTimeout(20000); HttpResponse res = h.send(req); if(res.getStatusCode() == 200) { ... }
Testing: Salesforce does not make real callouts in tests. Implement the HttpCalloutMock interface and register it with Test.setMock(HttpCalloutMock.class, new MyMock()). The mock returns a predefined HttpResponse. Use MultiStaticResourceCalloutMock for multi-callout tests.
Timeout: req.setTimeout() accepts milliseconds (1000–120000). Always set a timeout to avoid transactions hanging indefinitely.
Always test both success and error response codes, and verify idempotent retry logic.
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.