In Salesforce Apex, a consumer example demonstrates how code reads and processes external data, such as JSON payloads from callouts, Platform Events, or Named Credentials. This evergreen guide walks through verified patterns for deserializing JSON, handling errors, and mapping fields into sObjects or custom types. You will see concrete Apex consumer examples for REST services, Streaming API, and asynchronous messaging, plus checks for security, governor limits, and retry behavior. Use these patterns to build reliable integrations that remain stable across releases.
What is an Apex Consumer
An Apex consumer is code that requests or receives data from an external source and then processes it in Salesforce. Common sources include HTTP callouts to REST APIs, Streaming API or Platform Event subscriptions, and future or queueable methods that handle asynchronous work. A well built consumer parses JSON or XML, maps fields to Salesforce objects, handles faults gracefully, and respects governor limits. Because every integration touches reliability, security, and data integrity, treating each consumer as a production component is a best practice.
Key Concepts and Terms
Understanding core terms helps you read and write Apex consumers with confidence. These concepts shape how data moves into Salesforce and how it is handled once it arrives.
HTTP Callouts and Apex
An HTTP callout lets Apex send requests to external services and read the response. You typically use Http, HttpRequest, and HttpResponse classes, set headers, manage authentication, and then deserialize the response body. Successful consumers check status codes, parse JSON safely, and implement retry or logging when callouts fail.
Platform Events and Streaming API
Platform Events are Salesforce native messages that support event driven architectures, while Streaming API pushes changes from standard or custom objects. When your Apex subscribes to these sources, you build consumer logic in trigger or handler classes, process events in asynchronous methods, and acknowledge successful processing to avoid redelivery.
Governor Limits and Consumer Design
Governor limits protect shared resources, so every consumer must be designed with limits in mind. Key limits for consumers include callout timeouts, heap size, CPU time, and the number of future or queueable jobs. Design consumers to use streaming pagination, selective queries, and bulk deserialization to stay within limits at scale.
Verified Apex Consumer Example Patterns
The following patterns reflect commonly used, verified approaches for building Apex consumers. They focus on readability, test coverage, and safe error handling, so you can adapt them to your integration scenarios.
Pattern 1: Synchronous REST Callout with JSON2Apex
Use Http and HttpRequest to call a REST endpoint, then deserialize the response into generated Apex classes. This pattern works well for simple, low latency integrations where you can map the response to known shapes.
Pattern 2: Asynchronous Callout with Queueable
Move long running callouts out of synchronous transactions by chaining HttpRequestCallout followed by a Queueable or Future method. This pattern avoids mixed DML and governor limit issues, and it provides a natural place for retry and logging logic.
Pattern 3: Platform Event Trigger Consumer
Subscribe to a Platform Event with a trigger or handler, parse the fields, and insert or update records in the same or a related object. This pattern supports loose coupling and can be kept stateless to simplify debugging and replay.
Pattern 4: Streaming API PushTopic Consumer
Pattern 4: Streaming API PushTopic Consumer
Use Streaming API with PushTopic or CometD to receive real time updates, then process records in Apex via trigger or platform event consumers. This pattern suits dashboards, near real time alerts, and cases where you need lightweight, low latency notifications.
Comparison of Common Consumer Approaches
Different integration styles suit different scenarios. The table below compares key approaches so you can choose the right consumer pattern for your use case.
| Approach | Typical Use Case | Asynchronous Capable | Built In Retry | Best Fit For |
|---|---|---|---|---|
| Synchronous Http Callout | Lightweight request response | No | Manual | Fast, simple APIs with small payloads |
| Queueable or Future Callout | Long running or bulk callouts | Yes | Manual | Jobs that exceed synchronous limits |
| Platform Event Trigger | Event driven processing | Yes | At least once delivery | Loose coupling and replay scenarios |
| Streaming API PushTopic | Real time updates to UI or logic | Yes via CometD | Session based reconnection | Near real time dashboards and alerts |
Design Considerations for Apex Consumers
Building reliable consumers requires attention to error handling, idempotency, and monitoring. The decisions you make here affect uptime, data quality, and support burden.
Error Handling and Retry
Consumers should inspect status codes, parse error bodies, and apply exponential backoff for transient failures. For asynchronous patterns, leverage Platform Event best effort delivery or implement deduplication IDs to avoid double processing. Log key details so you can diagnose callouts that fail in production.
Security and Authentication
Use Named Credentials to manage endpoints, certificates, and authentication headers. Scoped OAuth tokens, connected apps, and certificate auth reduce secret sprawl. Always enforce TLS, validate input, and sanitize fields before DML to reduce injection and overposting risks.
Data Mapping and Idempotency
Map external fields to Salesforce fields deliberately, using deterministic transformations and standard naming conventions. Design consumers to be idempotent when possible, using external IDs or unique transaction IDs to ensure that retries do not create duplicates or overwrite newer data.
Testing and Monitoring
Write unit tests that mock callouts with System.mock and HttpCalloutMock. Cover success, partial failure, and error paths. Monitor callout timeouts, heap usage, and asynchronous job queues with OrgMetrics or EventBus metrics so you can spot bottlenecks before they impact users.
Common Pitfalls and How to Avoid Them
- Large JSON payloads that exceed heap limits: Stream or paginate data, and avoid building huge intermediate maps in memory.
- Untyped or loosely parsed JSON: Use defined classes or DOM methods so field changes are caught at compile time or in tests.
- Callouts in synchronous context that time out: Move to Queueable or Future and set reasonable timeouts on HttpRequest.
- Unhandled deserialization errors: Use try/catch around deserialize and add fallback logic for missing or malformed fields.
- Missing idempotency: Use deduplication keys, external IDs, or upsert logic to avoid duplicate records on retry.
When to Choose Which Pattern
Choose your consumer approach based on payload size, latency requirements, and failure tolerance. For small, quick requests, a synchronous callout is acceptable if you handle timeouts and retries. For heavy or long running work, use Queueable or Future. Prefer Platform Events when you need event sourcing or replay, and Streaming API when you need real time push to connected apps.
Conclusion
Apex consumer examples are practical templates you can adapt to callouts, Platform Events, and Streaming API scenarios. By using verified patterns, handling errors, securing authentication, and monitoring performance, you can integrate external data into Salesforce reliably. Treat each consumer as a first class component, document contracts, and design for scale so your integrations remain stable as APIs and business needs evolve.