sf-api-design
Skill15 starsChanged 7 months agoMITView on GitHub
Salesforce API design — custom REST endpoints, batch operations, Composite API, error envelopes, auth. Use when designing APIs exposed from Salesforce. Do NOT use for outbound callouts or Platform Events.
In this repository58 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- asideSkill
- checkpointSkill
- configure-sccSkill
- continuous-agent-loopSkill
- mcp-server-patternsSkill
- model-routeSkill
- prompt-optimizerSkill
- refactor-cleanSkill
- resume-sessionSkill
- save-sessionSkill
- search-firstSkill
- security-scanSkill
- sessionsSkill
- sf-2gp-security-reviewSkill
- sf-agentforce-developmentSkill
- sf-agentforce-mcp-actionsSkill
- sf-apex-async-patternsSkill
- sf-apex-best-practicesSkill
- sf-apex-constraintsSkill
- sf-apex-cursorSkill
- sf-apex-enterprise-patternsSkill
- sf-apex-testingSkill
- sf-approval-processesSkill
- sf-aura-developmentSkill
- sf-build-fixSkill
- sf-cli-referenceSkill
- sf-data-modelingSkill
- sf-debuggingSkill
- sf-deployment-constraintsSkill
- sf-deploymentSkill
- sf-devops-ci-cdSkill
- sf-docs-lookupSkill
- sf-e2e-testingSkill
- sf-experience-cloudSkill
- sf-flow-developmentSkill
- sf-governor-limitsSkill
- sf-harness-auditSkill
- sf-helpSkill
- sf-integrationSkill
- sf-lwc-constraintsSkill
- sf-lwc-developmentSkill
- sf-lwc-testingSkill
- sf-metadata-managementSkill
- sf-platform-events-cdcSkill
- sf-quickstartSkill
- sf-security-constraintsSkill
- sf-securitySkill
- sf-soql-constraintsSkill
- sf-soql-optimizationSkill
- sf-tdd-workflowSkill
- sf-testing-constraintsSkill
- sf-trigger-constraintsSkill
- sf-trigger-frameworksSkill
- sf-visualforce-developmentSkill
- strategic-compactSkill
- update-docsSkill
- update-platform-docsSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 224
Use WITH USER_MODE in SOQL and AccessLevel.USER_MODE in DML
- Very specific: line 225
Use Security.stripInaccessible() when you need field-level enforcement on DML -- check getRemovedFields() for critical fields
- Distinctive: line 227
Use proper HTTP status codes (200, 201, 400, 404, 500)
- Very specific: line 230
Use Database.insert(records, false) for bulk APIs to support partial success
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Salesforce API Design
Patterns for designing and implementing custom APIs on the Salesforce platform. Callout limits, Composite API limits, and Named Credential details live in the reference file.
@../_reference/INTEGRATION_PATTERNS.md
When to Use
- Designing custom REST or SOAP APIs exposed from Salesforce using Apex
- Establishing consistent API response envelopes and error handling patterns
- Configuring authentication for inbound API access
- Building batch REST endpoints for bulk operations
- Reviewing Apex API code for security (CRUD/FLS, input validation, status codes)
Custom REST API Pattern
@RestResource(urlMapping='/api/accounts/*')
global with sharing class AccountAPI {
@HttpGet
global static void getAccount() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
String accountId = req.requestURI.substringAfterLast('/');
try {
Account acc = [
SELECT Id, Name, Industry, AnnualRevenue
FROM Account WHERE Id = :accountId
WITH USER_MODE LIMIT 1
];
res.statusCode = 200;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(true, acc, null)));
} catch (QueryException e) {
res.statusCode = 404;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(false, null, 'Account not found')));
} catch (Exception e) {
res.statusCode = 500;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(false, null, 'An internal error occurred')));
}
}
@HttpPost
global static void createAccount() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
try {
Object parsed = JSON.deserializeUntyped(req.requestBody.toString());
if (!(parsed instanceof Map<String, Object>)) {
res.statusCode = 400;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(false, null,
'Expected JSON object, got ' +
(parsed instanceof List<Object> ? 'array' : 'primitive')
)));
return;
}
Map<String, Object> body = (Map<String, Object>) parsed;
Account acc = new Account(
Name = (String) body.get('name'),
Industry = (String) body.get('industry')
);
// stripInaccessible — check getRemovedFields() to avoid silent data loss
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.CREATABLE, new List<Account>{acc});
if (!decision.getRemovedFields().isEmpty()) {
res.statusCode = 403;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(false, null,
'Insufficient field permissions for: ' +
decision.getRemovedFields())));
return;
}
insert decision.getRecords();
res.statusCode = 201;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(true, decision.getRecords()[0], null)));
} catch (Exception e) {
res.statusCode = 400;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(false, null, e.getMessage())));
}
}
global class ApiResponse {
public Boolean success;
public Object data;
public String error;
public ApiResponse(Boolean success, Object data, String error) {
this.success = success;
this.data = data;
this.error = error;
}
}
}Batch REST Endpoint Pattern
@HttpPost
global static void bulkCreate() {
RestRequest req = RestContext.request;
RestResponse res = RestContext.response;
try {
List<Object> items = (List<Object>) JSON.deserializeUntyped(
req.requestBody.toString());
List<Account> accounts = new List<Account>();
for (Object item : items) {
Map<String, Object> fields = (Map<String, Object>) item;
accounts.add(new Account(
Name = (String) fields.get('name'),
Industry = (String) fields.get('industry')
));
}
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.CREATABLE, accounts);
List<Database.SaveResult> results =
Database.insert(decision.getRecords(), false);
List<Object> response = new List<Object>();
for (Integer i = 0; i < results.size(); i++) {
Map<String, Object> row = new Map<String, Object>();
row.put('index', i);
row.put('success', results[i].isSuccess());
row.put('id', results[i].isSuccess() ? results[i].getId() : null);
if (!results[i].isSuccess()) {
row.put('errors', results[i].getErrors()[0].getMessage());
}
response.add(row);
}
res.statusCode = 200;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(true, response, null)));
} catch (Exception e) {
res.statusCode = 400;
res.responseBody = Blob.valueOf(JSON.serialize(
new ApiResponse(false, null, e.getMessage())));
}
}Error Handling Patterns
Structured error codes for API consumers:
global class ApiError {
public String code;
public String message;
public String field;
public ApiError(String code, String message, String field) {
this.code = code;
this.message = message;
this.field = field;
}
}
// Standard error codes:
// FIELD_REQUIRED — Missing required field
// RECORD_NOT_FOUND — Record ID doesn't exist or no access
// GOVERNOR_LIMIT — Operation would exceed governor limits
// INSUFFICIENT_ACCESS — User lacks CRUD/FLS permission
// VALIDATION_FAILED — Validation rule or trigger prevented save
// DUPLICATE_VALUE — Unique field constraint violatedAuthentication for Inbound APIs
| Method | Use When | Setup |
| Named Principal | All API users share one Salesforce user | Connected App + single auth |
| Per-User | Each API caller maps to a Salesforce user | Connected App + OAuth per user |
| JWT Bearer | Server-to-server, no user interaction | Connected App + X.509 certificate |
| API Key (Custom) | Simple external tools | Custom Metadata + header validation |
Anti-Patterns
| Anti-Pattern | Problem | Fix |
| God endpoint (all CRUD in one method) | Hard to maintain and test | One method per operation (@HttpGet, @HttpPost) |
| No pagination | Timeouts, governor limits | Add LIMIT + OFFSET or cursor-based pagination |
| Exposing internal Salesforce IDs | Security risk, breaks across orgs | Use external IDs or custom identifiers |
| No error codes | Consumers can't programmatically handle errors | Return structured error codes |
| No API versioning | Breaking changes affect all consumers | Version via URL path: /api/v1/accounts/ |
WITHOUT SHARING on API class | Bypasses record-level security | Use WITH SHARING on REST resources |
| Returning all fields | Wastes bandwidth, exposes sensitive data | Return only requested/needed fields |
Best Practices
- Use
WITH USER_MODEin SOQL andAccessLevel.USER_MODEin DML - Use
Security.stripInaccessible()when you need field-level enforcement on DML -- checkgetRemovedFields()for critical fields - Return consistent response envelopes (success, data, error)
- Use proper HTTP status codes (200, 201, 400, 404, 500)
- Implement rate limiting awareness (API request limits)
- Version APIs via URL path (
/api/v1/accounts/) - Use
Database.insert(records, false)for bulk APIs to support partial success
Related
- Constraints: sf-security-constraints
- Reference: @../_reference/INTEGRATION_PATTERNS.md
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

